LeetCode——Spiral Matrix II
2014-11-19 14:43
323 查看
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:
原题链接:https://oj.leetcode.com/problems/spiral-matrix-ii/
之前的一题是将螺旋结构的二维数组转成一维数组,此题正好相反,故只需将原来的位置上取下来的元素放回去。
public class SpiralMatrixII {
public static void main(String[] args) {
int[][] matrix = new SpiralMatrixII().generateMatrix(3);
for(int[] r : matrix){
for(int c : r)
System.out.print(c + "\t");
System.out.println();
}
}
public int[][] generateMatrix(int n) {
int[][] matrix = new int
;
if(n == 0)
return matrix;
int l = 0, r = matrix[0].length - 1;
int u = 0, d = matrix.length - 1;
int num = 1;
while (l <= r && u <= d) {
for (int i = l; i <= r; i++)
matrix[u][i] = num++;
u++;
if (u > d)
continue;
for (int i = u; i <= d; i++)
matrix[i][r] = num++;
r--;
if (l > r)
continue;
for (int i = r; i >= l; i--)
matrix[d][i] = num++;
d--;
if (u > d)
continue;
for (int i = d; i >= u; i--)
matrix[i][l] = num++;
l++;
}
return matrix;
}
}
For example,
Given n =
3,
You should return the following matrix:
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
原题链接:https://oj.leetcode.com/problems/spiral-matrix-ii/
之前的一题是将螺旋结构的二维数组转成一维数组,此题正好相反,故只需将原来的位置上取下来的元素放回去。
public class SpiralMatrixII {
public static void main(String[] args) {
int[][] matrix = new SpiralMatrixII().generateMatrix(3);
for(int[] r : matrix){
for(int c : r)
System.out.print(c + "\t");
System.out.println();
}
}
public int[][] generateMatrix(int n) {
int[][] matrix = new int
;
if(n == 0)
return matrix;
int l = 0, r = matrix[0].length - 1;
int u = 0, d = matrix.length - 1;
int num = 1;
while (l <= r && u <= d) {
for (int i = l; i <= r; i++)
matrix[u][i] = num++;
u++;
if (u > d)
continue;
for (int i = u; i <= d; i++)
matrix[i][r] = num++;
r--;
if (l > r)
continue;
for (int i = r; i >= l; i--)
matrix[d][i] = num++;
d--;
if (u > d)
continue;
for (int i = d; i >= u; i--)
matrix[i][l] = num++;
l++;
}
return matrix;
}
}
相关文章推荐
- 《leetcode》spiral-matrix-ii(构造螺旋矩阵)
- leetcode-Spiral Matrix II
- LeetCode54/59 Spiral Matrix I/II
- LeetCode 59 Spiral Matrix II
- LeetCode-Spiral Matrix II
- 【LeetCode】Spiral Matrix II
- [leetcode] 59.Spiral Matrix II
- LeetCode Spiral Matrix II
- [LeetCode]Spiral Matrix II
- Leetcode 细节实现题 Spiral Matrix II
- [LeetCode] Spiral Matrix II
- [LeetCode] Spiral Matrix II
- leetcode: Spiral Matrix II
- Leetcode 59. Spiral Matrix II
- LeetCode-Spiral Matrix II
- LeetCode - Spiral Matrix I && II - Frequent
- LeetCode Spiral Matrix II
- LeetCode 59 Spiral Matrix II
- leetcode — spiral-matrix-ii
- LeetCode-59-Spiral Matrix II(C语言实现)