# [leetcode-59]spiral matrixII(java)

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 int[][] generateMatrix(int n) {
int[][] result = new int[n][n];
//init result
for(int i = 0;i<n;i++)
for(int j = 0;j<n;j++)
result[i][j] = 0;

int index = 0;
int num = n*n;
int row = 0,col = -1;
while(index<num){
for(col = col+1;col<n;col++){
if(result[row][col]!=0)
break;
result[row][col] = ++index;
}
col--;
for(row = row+1;row<n;row++){
if(result[row][col]!=0)
break;
result[row][col] = ++index;
}
row--;
for(col = col-1;col>=0;col--){
if(result[row][col] != 0)
break;
result[row][col] = ++index;
}
col++;
for(row = row-1;row>=0;row--){
if(result[row][col] != 0)
break;
result[row][col] = ++index;
}
row++;
}
return result;
}

#### Spiral Matrix && Spiral MatrixII

2014-11-07 22:00:44

#### 【LeetCode-59】Spiral Matrix II

2016-04-01 17:24:26

#### LeetCode 059 Spiral MatrixII

2014-02-10 10:20:55

#### leetcode-59 Spiral Matrix II

2016-11-04 09:48:20

#### leetcode-59 Spiral Matrix

2017-04-07 15:22:25

#### [Leetcode]Spiral MatrixII

2015-11-16 19:56:45

#### 【LeetCode-面试算法经典-Java实现】【054-Spiral Matrix（螺旋矩阵）】

2015-07-29 06:49:20

#### 54. Spiral Matrix (重要！！！)

2016-07-17 23:01:15

#### 1105. Spiral Matrix (25) 排序、模拟

2016-04-06 14:39:28

#### 54. Spiral Matrix(unsolved) && Spiral MatrixII(unsolved)

2017-03-30 18:08:34