package Level3;
/**
* Spiral Matrix II
*
* Given an integer n, generate a square matrix filled with elements from 1 to
* n2 in spiral order.
*
* For example, Given n = 3,
*
* You should return the following matrix: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5
* ] ]
*
*/
public class S59 {
public static void main(String[] args) {
int[][] A = generateMatrix(5);
for(int i=0; i<A.length; i++){
for(int j=0; j<A[0].length; j++){
System.out.print(A[i][j] + " ");
}
System.out.println();
}
}
public static int[][] generateMatrix(int n) {
int[][] A = new int[n][n];
int num = 1;
int i, j;
int level = 0;
while(num < n*n){
// 向左从level填到n-1-level
for(j=level; j<n-1-level; j++){
A[level][j] = num++;
}
// 向下从level填到n-1-level
for(i=level; i<n-1-level; i++){
A[i][n-1-level] = num++;
}
// 向左从n-1-level填到level
for(j=n-1-level; j>level; j--){
A[n-1-level][j] = num++;
}
// 向上从n-1-level填到level
for(i=n-1-level; i>level; i--){
A[i][level] = num++;
}
level++;
}
// 对于n为奇数情况,要额外添加一个数
if((n&1) == 1){
A[n/2][n/2] = num;
}
return A;
}
}
参考http://leetcodenotes.wordpress.com/2013/11/23/leetcode-spiral-matrix-%E6%8A%8A%E4%B8%80%E4%B8%AA2d-matrix%E7%94%A8%E8%9E%BA%E6%97%8B%E6%96%B9%E5%BC%8F%E6%89%93%E5%8D%B0/
四条边bound的方法
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
int k = 1;
int top = 0, bottom = n - 1, left = 0, right = n - 1;
while (left < right && top < bottom) {
for (int j = left; j < right; j++) {
res[top][j] = k++;
}
for (int i = top; i < bottom; i++) {
res[i][right] = k++;
}
for (int j = right; j > left; j--) {
res[bottom][j] = k++;
}
for (int i = bottom; i > top; i--) {
res[i][left] = k++;
}
left++;
right--;
top++;
bottom--;
}
if (n % 2 != 0)
res[n / 2][n / 2] = k;
return res;
}
public class Solution {
public int[][] generateMatrix(int n) {
int rows = n-1, cols = n-1; // last row and col
int level = 0;
int[][] ret = new int[n][n];
int cnt = 1;
while(cnt < n*n){
for(int j=level; j<cols-level; j++){
ret[level][j] = cnt++;
}
for(int i=level; i<rows-level; i++){
ret[i][cols-level] = cnt++;
}
for(int j=cols-level; j>level; j--){
ret[rows-level][j] = cnt++;
}
for(int i=rows-level; i>level; i--){
ret[i][level] = cnt++;
}
level++;
}
if(n%2 == 1){
ret[n/2][n/2] = n*n;
}
return ret;
}
}