Java 版本代码如下:
public int[][] generateMatrix(int n) { int[][] res = new int[n][n]; int value = 1; int left = 0, right = n-1, top = 0, bottom = n-1; while(top < bottom && left < right) { //corresponding to the red part for(int j = left; j < right; j++) { res[top][j] = value++; } //corresponding to the blue part for(int i = top; i < bottom; i++) { res[i][right] = value++; } //corresponding to the yellow part for(int j = right; j > left; j--) { res[bottom][j] = value++; } //corresponding to the purple part for(int i = bottom; i > top; i--) { res[i][left] = value++; } top++; bottom--; left++; right--; } if(n%2!=0) res[n/2][n/2]=value; return res; }
思路,定义四个变量 top, bottom, left, right分别bound住四边。然后可以按照下图的方法填充res矩阵。填充顺序是(1) 红色,(2) 蓝色,(3) 绿色,(4) 紫色。
把最外面填充完全后。开始top++, bottom--, left++, right--来把四个边往里面移。
* 如果n是奇数,最后中间那个值要单独处理, res[n/2][n/2] = k.
原题:
转载至: