59.Spiral Matrix II
题目链接:https://leetcode.com/problems/spiral-matrix-ii/description/
题目大意:构造蛇形矩阵。
法一:模板模拟。代码如下(耗时2ms):
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public int[][] generateMatrix(int n) { 2 int[][] res = new int[n][n]; 3 if(n == 0) { 4 return res; 5 } 6 int i = 0, j = 0, num = 1; 7 res[i][j] = num; 8 while(num < n * n) { 9 //从左往后 10 while(j < n - 1 && res[i][j + 1] == 0) { 11 res[i][++j] = ++num; 12 } 13 //从上到下 14 while(i < n - 1 && res[i + 1][j] == 0) { 15 res[++i][j] = ++num; 16 } 17 //从右到左 18 while(j > 0 && res[i][j - 1] == 0) { 19 res[i][--j] = ++num; 20 } 21 //从下到上 22 while(i > 0 && res[i - 1][j] == 0) { 23 res[--i][j] = ++num; 24 } 25 } 26 return res; 27 }