Skip to content

Commit 63d50ef

Browse files
committed
Merge branch 'master' of github.com:g1patil/data-structures-and-algorithms
2 parents 1da69de + a35bed7 commit 63d50ef

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
package matrix;
2+
3+
import lists.ListNode;
4+
5+
public class SpiralMatricIV {
6+
public int[][] spiralMatrix(int m, int n, ListNode head) {
7+
int[][] matrix = init(m, n);
8+
int[] direction = {1,0,0};
9+
ListNode temp = head;
10+
11+
while(temp!=null){
12+
int value = temp.val;
13+
temp = temp.next;
14+
matrix[direction[1]][direction[2]] = value;
15+
updateDirection(direction,matrix);
16+
}
17+
18+
return matrix;
19+
}
20+
21+
private int[][] init(int row,int col){
22+
int[][] matrix = new int[row][col];
23+
for(int i=0;i<row;i++){
24+
for(int j=0;j<col;j++){
25+
matrix[i][j] = -1;
26+
}
27+
}
28+
return matrix;
29+
}
30+
31+
private void updateDirection(int[] direction,int[][] matrix){
32+
int currentDirection = direction[0];
33+
if(currentDirection == 1){
34+
if(!changeDirection(direction[1],direction[2],matrix)){
35+
direction[2]++;
36+
} else {
37+
direction[0] = 2;
38+
direction[1]++;
39+
}
40+
}
41+
if(currentDirection == 2){
42+
if(!changeDirection(direction[1],direction[2],matrix)){
43+
direction[1]++;
44+
} else {
45+
direction[0] = 3;
46+
direction[2]--;
47+
}
48+
}
49+
50+
if(currentDirection == 3){
51+
if(!changeDirection(direction[1],direction[2],matrix)){
52+
direction[2]--;
53+
} else {
54+
direction[0] = 4;
55+
direction[1]--;
56+
}
57+
}
58+
if(currentDirection == 4){
59+
if(!changeDirection(direction[1],direction[2],matrix)){
60+
direction[1]--;
61+
} else {
62+
direction[0] = 1;
63+
direction[2]++;
64+
}
65+
}
66+
}
67+
68+
private boolean changeDirection(int row,int col,int[][] matrix){
69+
return row == matrix.length-1 | col == matrix[0].length-1;
70+
}
71+
72+
public static void main(String[] args) {
73+
ListNode n1 = new ListNode(1);
74+
ListNode n2 = new ListNode(2);
75+
ListNode n3 = new ListNode(3);
76+
77+
n1.setNext(n2);
78+
n2.setNext(n3);
79+
80+
MatrixUtility.print(new SpiralMatricIV().spiralMatrix(1,3,n1));
81+
}
82+
}

0 commit comments

Comments
 (0)