-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpiralMatrix.java
More file actions
52 lines (46 loc) · 1.44 KB
/
Copy pathSpiralMatrix.java
File metadata and controls
52 lines (46 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
//spiral
import java.util.*;
class firstclass {
public static void spiral(int matrix[][]) {
int startRow = 0;
int startCol = 0;
int endRow = matrix.length-1;
int endCol = matrix[0].length-1;
while(startRow <= endRow && startCol <= endCol) {
// top
for(int j = startCol; j <=endCol; j += 1) {
System.out.print(matrix[startRow][j] + " ");
}
// right
for(int i = startRow+1; i <= endRow; i += 1) {
System.out.print(matrix[i][endCol] + " ");
}
// bottom
for(int j = endCol-1; j >= startCol; j -= 1) {
if(startRow == endRow) {
break;
}
System.out.print(matrix[endRow][j] + " ");
}
// left
for(int i = endRow-1; i >= startRow+1; i -= 1) {
if(startCol == endCol) {
break;
}
System.out.print(matrix[i][startCol] + " ");
}
startCol++;
startRow++;
endCol--;
endRow--;
}
System.out.print("\n");
}
public static void main(String args[]) {
int matrix[][] = {{1 , 2 , 3 , 4},
{5 , 6 , 7 , 8},
{9 , 10 , 11 , 12},
{13 , 14 , 15 , 16}};
spiral(matrix);
}
}