File tree Expand file tree Collapse file tree 1 file changed +67
-0
lines changed
Expand file tree Collapse file tree 1 file changed +67
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments