public class DayCode {
public static void main(String[] args) {
int n = 3;
int[][] ans = new DayCode().generateMatrix(n);
System.out.println(Arrays.deepToString(ans));
}
/**
* 题目链接: https://leetcode-cn.com/problems/spiral-matrix-ii/
* 时间复杂度 O(n)
* 空间复杂度 O(n * n)
*
* @param n
* @return
*/
public int[][] generateMatrix(int n) {
int[][] ans = new int[n][n];
boolean[][] visited = new boolean[n][n];
int[][] directions = new int[][]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int directionIdx = 0;
int row = 0;
int col = 0;
for (int i = 1; i <= n * n; i++) {
ans[row][col] = i;
visited[row][col] = true;
int nextRow = row + directions[directionIdx][0];
int nextCol = col + directions[directionIdx][1];
if (nextRow < 0 || nextRow >= n || nextCol < 0 || nextCol >= n || visited[nextRow][nextCol]) {
directionIdx = (directionIdx + 1) % 4;
}
row += directions[directionIdx][0];
col += directions[directionIdx][1];
}
return ans;
}
}
评论