Skip to content

Commit 8b41dd1

Browse files
Spiral order printing of a matrix
1 parent d7c80f9 commit 8b41dd1

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

Matrix/Spiral.kt

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package Matrix
2+
3+
fun main(args : Array<String>){
4+
val matrix = arrayOf(
5+
arrayOf(1,2,3,4,5),
6+
arrayOf(3,4,5,6,7),
7+
arrayOf(4,5,6,7,8),
8+
arrayOf(6,7,8,9,10)
9+
)
10+
11+
printSpiral(matrix)
12+
}
13+
14+
private fun printSpiral(matrix : Array<Array<Int>>){
15+
var top = 0
16+
var left = 0
17+
var right = matrix[0].size-1
18+
var bottom = matrix.size-1
19+
20+
while(true){
21+
if(left > right){
22+
break
23+
}
24+
25+
// Printing the top row of the matrix
26+
for(i in left..right){
27+
println(" " + matrix[top][i])
28+
}
29+
30+
// After printing the top row, narrow down the matrix
31+
top++
32+
33+
if(top>bottom){
34+
break
35+
}
36+
37+
// Printing the right column
38+
for(i in top..bottom){
39+
println(" " + matrix[i][right])
40+
}
41+
42+
// After printing the right column, narrow down the area from the right side
43+
right--
44+
45+
if(left>right){
46+
break
47+
}
48+
49+
// Printing the bottom row
50+
for(i in right.downTo(left)){
51+
println(" " + matrix[bottom][i])
52+
}
53+
54+
// After printing the bottom row, narrow down the area from the bottom
55+
bottom--
56+
57+
if(top > bottom){
58+
break
59+
}
60+
61+
// Printing out the left column
62+
for(i in bottom.downTo(top)){
63+
println(" " + matrix[i][left])
64+
}
65+
left++
66+
}
67+
}

0 commit comments

Comments
 (0)