【leetcode】59. Spiral Matrix II
2016-12-14 15:47
302 查看
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n =
You should return the following matrix:
public class Solution {
public int[][] generateMatrix(int n) {
int[][] matrix = new int
;
if (n == 0){
return matrix;
}
int rowBegin = 0;
int rowEnd = n-1;
int colBegin = 0;
int colEnd = n-1;
int num = 1;
while (rowBegin <= rowEnd && colBegin <= colEnd){
for (int j = colBegin; j <= colEnd; j++){
matrix[rowBegin][j] = num++;
}
rowBegin++;
for (int j = rowBegin; j <= rowEnd; j++){
matrix[j][colEnd] = num++;
}
colEnd--;
//对于n*n矩阵此处的if判断可去掉
if (rowBegin <= rowEnd){
for (int j = colEnd; j >= colBegin; j--){
matrix[rowEnd][j] = num++;
}
}
rowEnd--;
if (colBegin <= colEnd){
for (int j = rowEnd; j >= rowBegin; j--){
matrix[j][colBegin] = num++;
}
}
colBegin++;
}
return matrix;
}
}
For example,
Given n =
3,
You should return the following matrix:
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]]
public class Solution {
public int[][] generateMatrix(int n) {
int[][] matrix = new int
;
if (n == 0){
return matrix;
}
int rowBegin = 0;
int rowEnd = n-1;
int colBegin = 0;
int colEnd = n-1;
int num = 1;
while (rowBegin <= rowEnd && colBegin <= colEnd){
for (int j = colBegin; j <= colEnd; j++){
matrix[rowBegin][j] = num++;
}
rowBegin++;
for (int j = rowBegin; j <= rowEnd; j++){
matrix[j][colEnd] = num++;
}
colEnd--;
//对于n*n矩阵此处的if判断可去掉
if (rowBegin <= rowEnd){
for (int j = colEnd; j >= colBegin; j--){
matrix[rowEnd][j] = num++;
}
}
rowEnd--;
if (colBegin <= colEnd){
for (int j = rowEnd; j >= rowBegin; j--){
matrix[j][colBegin] = num++;
}
}
colBegin++;
}
return matrix;
}
}
相关文章推荐
- Leetcode 59. Spiral Matrix II
- LeetCode 59. Spiral Matrix II
- LeetCode59——Spiral Matrix II
- [LeetCode 59] Spiral Matrix II
- leetcode 59: Spiral Matrix II
- LeetCode 59: Spiral Matrix II
- LeetCode 59 Spiral Matrix II
- [leetcode] 59.Spiral Matrix II
- LeetCode------54. Spiral Matrix(螺旋二维矩阵)-----59. Spiral Matrix II(n的螺旋矩阵)
- LeetCode 59 Spiral Matrix II(螺旋矩阵II)(Array)
- leetcode59 Spiral Matrix II
- <LeetCode OJ> 54 / 59 Spiral Matrix( I / II )
- 【leetcode】【59】Spiral Matrix II
- leetcode 59. Spiral Matrix II
- LeetCode59 Spiral Matrix II
- 【LeetCode】C# 59、Spiral Matrix II
- 【LeetCode】(59)Spiral Matrix II(Medium)
- leetcode 59. Spiral Matrix II
- LeetCode 54/59. Spiral Matrix i, ii
- [LeetCode]59. Spiral Matrix II