Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example 1:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
题目大意:环形遍历一个二维数组
这是这一类题目的最为常规的解法。
利用顶角(tr, tc)和下顶角的坐标(dr,dc),在打印完一个圆圈之后,进行tr++,tc++,dr--,dc--更新;
public List<Integer> spiralOrder(int[][] matrix) {
LinkedList<Integer> res = new LinkedList<>();
if (matrix == null || matrix.length ==0 ||matrix[0].length==0) return res;
int tr = 0,tc = 0;
int dr = matrix.length-1,dc = matrix[0].length-1;
while (tr<=dr&&tc<=dc){
printEdge(matrix,tr++,tc++,dr--,dc--,res);
}
return res;
}
public void printEdge(int[][] matrix, int tr,int tc,int dr,int dc,LinkedList<Integer> res){
if (tr == dr ){//only one row
for (int i = tc;i<=dc;i++){
res.add(matrix[tr][i]);
}
}else if (tc == dc){
for (int i = tr ;i<=dr;i++){
res.add(matrix[i][tc]);
}
}else {
int curc = tc;
int curr = tr;
while (curc!=dc){
res.add(matrix[tr][curc]);
curc++;
}
while (curr!=dr){
res.add(matrix[curr][dc]);
curr++;
}
while (curc!=tc){
res.add(matrix[dr][curc]);
curc--;
}
while (curr!=tr){
res.add(matrix[curr][tc]);
curr--;
}
}
}
Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
Example:
Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
int start =1;
public int[][] generateMatrix(int n) {
int [][] res = new int[n][n];
if (n<=0) return res;
int tr = 0,tc = 0;
int dr = res.length-1,dc = res[0].length-1;
while (tr<=dr&&tc<=dc){
printEdge(res,tr++,tc++,dr--,dc--);
}
return res;
}
public void printEdge(int[][] matrix,int tr,int tc,int dr,int dc){
if (tr == dr ){//only one row
for (int i = tc;i<=dc;i++){
matrix[tr][i] = start++;
}
}else if (tc == dc){
for (int i = tr ;i<=dr;i++){
matrix[tr][i] = start++;
}
}else {
int curc = tc;
int curr = tr;
while (curc!=dc){
matrix[tr][curc] = start++;
curc++;
}
while (curr!=dr){
matrix[curr][dc] = start++;
curr++;
}
while (curc!=tc){
matrix[dr][curc] = start++;
curc--;
}
while (curr!=tr){
matrix[curr][tc] = start++;
curr--;
}
}
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。