题目地址:
https://www.lintcode.com/problem/spiral-matrix-ii/description
给定一个正整数 n n n,返回一个 n × n n\times n n×n的矩阵,里面的数字恰好是 1 ∼ n 2 1\sim n^2 1∼n2,并且从 ( 0 , 0 ) (0,0) (0,0)按照右下左上的顺序依次填写。
可以按照四个方向顺次填写,当填到出界的位置或者之前已经填过的位置的时候,就回退一格然后向下一个方向继续填写。填写的同时记得计数一下已经填过的数字个数,当数字个数达到了 n 2 n^2 n2就退出循环。代码如下:
public class Solution {
/**
* @param n: An integer
* @return: a square matrix
*/
public int[][] generateMatrix(int n) {
// write your code here
int[][] res = new int[n][n];
// 按照右下左上记录四个方向
int[] d = {0, 1, 0, -1, 0};
int count = 0;
// 记录当前填写的位置
int x = 0, y = 0;
while (count < n * n) {
// 按四个方向依次遍历
for (int i = 0; i < 4; i++) {
// 当没出界并且当前位置没填,那就填,并计数加1
while (0 <= x && x < n && 0 <= y && y < n && res[x][y] == 0) {
res[x][y] = ++count;
x += d[i];
y += d[i + 1];
}
// 填到出界或者之前填过的位置的时候,先回退
x -= d[i];
y -= d[i + 1];
// 回退以后向下一个方向走一格,继续填写
x += d[(i + 1) % 4];
y += d[(i + 2) % 4];
}
}
return res;
}
}
时间复杂度 O ( n 2 ) O(n^2) O(n2),空间 O ( 1 ) O(1) O(1)。