螺旋矩阵 IV - 力扣 (LeetCode) 竞赛
![]()
1 /**
2 * Definition for singly-linked list.
3 * public class ListNode {
4 * int val;
5 * ListNode next;
6 * ListNode() {}
7 * ListNode(int val) { this.val = val; }
8 * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9 * }
10 */
11 class Solution {
12 public int[][] spiralMatrix(int m, int n, ListNode head) {
13 // 螺旋矩阵
14 int[][] matix = new int[m][n];
15 // 1.初始化
16 for(int i=0;i<m;i++){
17 for(int j=0;j<n;j++){
18 matix[i][j] = -1; // 如果不为-1表示访问过
19 }
20 }
21 // 2.遍历节点
22 int curr_row = 0;
23 int curr_col = 0;
24 int next_row = 0;
25 int next_col = 0;
26 int direct = 0; // 0表示向右、1表示向下、2表示向左、3表示向上
27 int[][] directs = {{0,1},{1,0},{0,-1},{-1,0}};
28 ListNode curr = head;
29 while(curr!=null){
30 // 插入
31 matix[curr_row][curr_col] = curr.val;
32 // 当前方向 0.向右
33 if(direct == 0){
34 next_row = curr_row+directs[0][0];
35 next_col = curr_col+directs[0][1];
36 if(next_col == n || matix[next_row][next_col] != -1){ // 到达最右
37 //改变方向 为下
38 direct = 1;
39 next_row = curr_row+directs[1][0];
40 next_col = curr_col+directs[1][1];
41 }
42 }else if(direct == 1){ // 1.下
43 next_row = curr_row+directs[1][0];
44 next_col = curr_col+directs[1][1];
45 if(next_row == m || matix[next_row][next_col] != -1){ // 到达最下
46 //改变方向 为左
47 direct = 2;
48 next_row = curr_row+directs[2][0];
49 next_col = curr_col+directs[2][1];
50 }
51 }else if(direct == 2){ // 2.左
52 next_row = curr_row+directs[2][0];
53 next_col = curr_col+directs[2][1];
54 if(next_col < 0 || matix[next_row][next_col] != -1){ // 到达最左
55 //改变方向 为上
56 direct = 3;
57 next_row = curr_row+directs[3][0];
58 next_col = curr_col+directs[3][1];
59 }
60 }else if(direct == 3){ // 3.上
61 next_row = curr_row+directs[3][0];
62 next_col = curr_col+directs[3][1];
63 if(next_row < 0 || matix[next_row][next_col] != -1){ // 到达最上
64 //改变方向 为右
65 direct = 0;
66 next_row = curr_row+directs[0][0];
67 next_col = curr_col+directs[0][1];
68 }
69 }
70 // 修改当前插入位置
71 curr_row = next_row;
72 curr_col = next_col;
73 // 向后
74 curr = curr.next;
75 }
76
77 return matix;
78 }
79
80 }