Sponsored
Sponsored
This approach traverses the matrix in a spiral order by systematically altering the direction when encountering the boundary or an already filled space. Start with the initial direction as 'right'. Change direction to 'down', 'left', 'up' as necessary when a boundary or an already filled cell is encountered.
1
2class ListNode:
3
The provided Python code defines a function spiralMatrix that takes the dimensions m, n and the head of a linked list. It begins by creating a m x n matrix initialized with -1. The spiral movement is driven by the dirs array, which holds possible movement directions. For each direction change, we ensure it keeps within valid boundaries or filled cell conditions. This implementation guarantees that the matrix is filled in a proper spiral order, transitioning directions when necessary.
In this approach, we fill the matrix in a spiral order by completing one 'layer' of the spiral at a time. Start filling from the outer layer to the inner layers progressively until the entire matrix is filled. Each layer comprises four segments: top row, right column, bottom row, and left column.
1class ListNode {
2 int val;
3 ListNode next;
4 ListNode() {}
5 ListNode(int val) { this.val = val; }
6 ListNode(int val, ListNode next) { this.val = val; this.next = next; }
7}
8
9public class SpiralMatrix {
10 public int[][] spiralMatrix(int m, int n, ListNode head) {
11 int[][] matrix = new int[m][n];
12 for (int[] row : matrix) {
13 Arrays.fill(row, -1);
14 }
15
16 int top = 0, bottom = m - 1, left = 0, right = n - 1;
17 while (head != null) {
18 for (int j = left; j <= right && head != null; j++) {
19 matrix[top][j] = head.val;
20 head = head.next;
21 }
22 top++;
23
24 for (int i = top; i <= bottom && head != null; i++) {
25 matrix[i][right] = head.val;
26 head = head.next;
27 }
28 right--;
29
30 for (int j = right; j >= left && head != null; j--) {
31 matrix[bottom][j] = head.val;
32 head = head.next;
33 }
34 bottom--;
35
36 for (int i = bottom; i >= top && head != null; i--) {
37 matrix[i][left] = head.val;
38 head = head.next;
39 }
40 left++;
41 }
42
43 return matrix;
44 }
45
46 public static void main(String[] args) {
47 ListNode head = new ListNode(3, new ListNode(0, new ListNode(2)));
48 SpiralMatrix sm = new SpiralMatrix();
49 int[][] result = sm.spiralMatrix(3, 5, head);
50
51 for (int[] row : result) {
52 for (int x : row) {
53 System.out.print(x + " ");
54 }
55 System.out.println();
56 }
57 }
58}
59The Java implementation manages a layer by tracking the limits of the current upward, downward, leftward, and rightward possible moves. The solution fills all available cells in these 'layers', transitioning from one direction to the next only after fully exhausting entries along the current path, and proceeds inward. The method completes filling the complete list coupled with the matrix traversal ensuring optimal manipulation through nested loops guarding respective limits.