MCPcopy Create free account
hub / github.com/Tiwarishashwat/InterviewCodes / spiralMatrix

Method spiralMatrix

spiralMatrix4.java:2–43  ·  view source on GitHub ↗
(int m, int n, ListNode head)

Source from the content-addressed store, hash-verified

1class Solution {
2 public int[][] spiralMatrix(int m, int n, ListNode head) {
3 int[][] matrix = new int[m][n];
4 for (int i = 0; i < m; i++) {
5 Arrays.fill(matrix[i], -1);
6 }
7
8 int topRow = 0, bottomRow = m - 1, leftCol = 0, rightCol = n - 1;
9 while (head != null) {
10 for (int col = leftCol; col <= rightCol; col++) {
11 if(head==null) break;
12 matrix[topRow][col] = head.val;
13 head = head.next;
14 }
15 topRow++;
16
17
18 for (int row = topRow; row <= bottomRow; row++) {
19 if(head==null) break;
20 matrix[row][rightCol] = head.val;
21 head = head.next;
22 }
23 rightCol--;
24
25
26 for (int col = rightCol; col >= leftCol ; col--) {
27 if(head==null) break;
28 matrix[bottomRow][col] = head.val;
29 head = head.next;
30 }
31 bottomRow--;
32
33
34 for (int row = bottomRow; row >= topRow ; row--) {
35 if(head==null) break;
36 matrix[row][leftCol] = head.val;
37 head = head.next;
38 }
39 leftCol++;
40 }
41
42 return matrix;
43 }
44}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected