Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
题意:给出矩阵的维数,将1-n^2的数填入螺旋矩阵中
思路:与LeetCode Spiral Matrix(螺旋矩阵)方法类似,只是一个逆过程而已
代码如下
public class Solution { public int[][] generateMatrix(int n) { int[][] matrix = new int[n][n]; int[][] dir = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; boolean[][] vis = new boolean[n][n]; int cnt = 0; int total = n * n; int cur = 0; int x = 0, y = 0; int nextx = 0, nexty = 0; while (cnt < total) { if (!vis[x][y]) { matrix[x][y] = cnt + 1; vis[x][y] = true; cnt++; } nextx = x + dir[cur][0]; nexty = y + dir[cur][1]; if (nextx < 0 || nextx >= n || nexty < 0 || nexty >= n || vis[nextx][nexty] == true) { cur = (cur + 1) % 4; continue; } x = nextx; y = nexty; } return matrix; } }