给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例 1:
输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
示例 2:
输入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/spiral-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
先遍历最外层,再遍历最里层。
package leetcode;
import java.util.ArrayList;
import java.util.List;
/**
* @author Livingdd
* 2019/8/12 20:49
**/
public class leet53 {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<>();
if (matrix == null || matrix.length == 0) return result;
//TODO:左上坐标为(x1,y1),右下坐标为(x2,y2)
int x1 = 0, y1 = 0;
int x2 = matrix.length - 1;
int y2 = matrix[0].length - 1;
while (x2 >= x1 && y2 >= y1) {
for (int i = y1; i <= y2; i++) result.add(matrix[x1][i]);
for (int i = x1 + 1; i <= x2; i++) result.add(matrix[i][y2]);
//TODO:当内层只剩一行或一列时,防止重复遍历
if (x1 == x2 || y1 == y2) break;
for (int i = y2 - 1; i >= y1; i--) result.add(matrix[x2][i]);
for (int i = x2 - 1; i >= x1 + 1; i--) result.add(matrix[i][y1]);
x1++;
y1++;
x2--;
y2--;
}
return result;
}
public static void main(String[] args) {
int[][] matrix = {{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
};
leet53 l = new leet53();
System.out.println(l.spiralOrder(matrix));
}
}