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#include <vector>
2
3struct ListNode {
4 int val;
5 ListNode *next;
6 ListNode(int x) : val(x), next(nullptr) {}
7};
8
9std::vector<std::vector<int>> spiralMatrix(int m, int n, ListNode* head) {
10 std::vector<std::vector<int>> matrix(m, std::vector<int>(n, -1));
11 int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
12 int dir_idx = 0;
13 int r = 0, c = 0;
14
15 for (int i = 0; head && i < m * n; ++i) {
16 matrix[r][c] = head->val;
17 head = head->next;
18
19 int nr = r + dirs[dir_idx][0], nc = c + dirs[dir_idx][1];
20
21 if (nr < 0 || nr >= m || nc < 0 || nc >= n || matrix[nr][nc] != -1) {
22 dir_idx = (dir_idx + 1) % 4;
23 nr = r + dirs[dir_idx][0];
24 nc = c + dirs[dir_idx][1];
25 }
26 r = nr;
27 c = nc;
28 }
29 return matrix;
30}
31
32// Example Usage
33int main() {
34 ListNode* head = new ListNode(3);
35 head->next = new ListNode(0);
36 head->next->next = new ListNode(2);
37 std::vector<std::vector<int>> result = spiralMatrix(3, 5, head);
38
39 for (const auto& row : result) {
40 for (int x : row) {
41 std::cout << x << " ";
42 }
43 std::cout << std::endl;
44 }
45
46 return 0;
47}
48
The C++ solution for generating a spiral matrix starts by creating an m x n
matrix initialized to -1
. We navigate the matrix using four possible directions: right, down, left, and up, changing to the next one upon hitting matrix boundaries or previously visited cells. The solution ensures correct traversal using a direction index to rotate among the directions, effectively filling the matrix according to the smart direction transitions while connected to the linked list traversal.
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.