59. Spiral Matrix II
2017-03-18 13:25
288 查看
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:
Subscribe to see which companies asked this question.
public class Solution {
public int[][] generateMatrix(int n) {
int[][] re = new int
;
int up = 0;
int down = n - 1;
int left = 0;
int right = n - 1;
int posi = 0;
int posj = 0;
int i = 0;
int sum = n * n;
while (i < sum) {
while (posj <= right) {
re[posi][posj] = i + 1;
posj++;
i++;
}
if (i == sum)
break;
posj--;
posi++;
up++;
while (posi <= down) {
re[posi][posj] = i + 1;
posi++;
i++;
}
if (i == sum)
break;
posi--;
posj--;
right--;
while (posj >= left) {
re[posi][posj] = i + 1;
posj--;
i++;
}
if (i == sum)
break;
posj++;
posi--;
down--;
while (posi >= up) {
re[posi][posj] = i + 1;
posi--;
i++;
}
if (i == sum)
break;
posi++;
posj++;
left++;
}
return re;
}
}
For example,
Given n =
3,
You should return the following matrix:
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
Subscribe to see which companies asked this question.
public class Solution {
public int[][] generateMatrix(int n) {
int[][] re = new int
;
int up = 0;
int down = n - 1;
int left = 0;
int right = n - 1;
int posi = 0;
int posj = 0;
int i = 0;
int sum = n * n;
while (i < sum) {
while (posj <= right) {
re[posi][posj] = i + 1;
posj++;
i++;
}
if (i == sum)
break;
posj--;
posi++;
up++;
while (posi <= down) {
re[posi][posj] = i + 1;
posi++;
i++;
}
if (i == sum)
break;
posi--;
posj--;
right--;
while (posj >= left) {
re[posi][posj] = i + 1;
posj--;
i++;
}
if (i == sum)
break;
posj++;
posi--;
down--;
while (posi >= up) {
re[posi][posj] = i + 1;
posi--;
i++;
}
if (i == sum)
break;
posi++;
posj++;
left++;
}
return re;
}
}
相关文章推荐
- LeetCode54/59 Spiral Matrix I/II
- Leetcode 59 Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- [LeetCode OJ]59. Spiral Matrix II
- LeetCode-59-Spiral Matrix II(Array)-Medium
- 54. Spiral Matrix&59. Spiral Matrix II
- [C语言][LeetCode][59]Spiral Matrix II
- LeetCode 59 Spiral Matrix II
- [59] Spiral Matrix II
- Leetcode 59. Spiral Matrix II
- 【C++】【LeetCode】54. Spiral Matrix && 59. Spiral Matrix II
- 【leetcode】Array——Spiral MatrixII(59)
- LeetCode_59---Spiral Matrix II
- 59. Spiral Matrix II
- [LeetCode 59] Spiral Matrix II
- 【LEETCODE】59-Spiral Matrix II
- [LeetCode]59. Spiral Matrix II
- leetcode 59. Spiral Matrix II
- 59. Spiral Matrix II