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 def __init__(self, val=0, next=None):
4 self.val = val
5 self.next = next
6
7
8def spiralMatrix(m, n, head):
9 # Initializing matrix with -1
10 matrix = [[-1] * n for _ in range(m)]
11 dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)] # Directions: right, down, left, up
12 dir_idx, r, c = 0, 0, 0
13
14 # Traverse the linked list
15 node = head
16 for i in range(m * n):
17 if node:
18 matrix[r][c] = node.val # Fill the current cell with node value
19 node = node.next
20 else:
21 break
22
23 nr, nc = r + dirs[dir_idx][0], c + dirs[dir_idx][1]
24
25 # Check if next position is valid
26 if 0 <= nr < m and 0 <= nc < n and matrix[nr][nc] == -1:
27 r, c = nr, nc
28 else:
29 # Change direction
30 dir_idx = (dir_idx + 1) % 4
31 r, c = r + dirs[dir_idx][0], c + dirs[dir_idx][1]
32
33 return matrix
34
35# Example Usage
36head = ListNode(3, ListNode(0, ListNode(2, ListNode(6, ListNode(8, ListNode(1))))))
37print(spiralMatrix(3, 5, head))
38
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;
The 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.