您的位置:首页 > 编程语言 > Java开发

LeetCode-54. Spiral Matrix (JAVA)(顺时针打印矩阵)

2017-04-17 15:44 417 查看

54. Spiral Matrix

Given a matrix of m x n elements (m rows,n columns), return all elements of the matrix in spiral order.

For example,

Given the following matrix:

[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]

You should return
[1,2,3,6,9,8,7,4,5]
.

解法1

public List<Integer> spiralOrder(int[][] arr) {
List<Integer> res = new ArrayList<>();
if (arr.length == 0)
return res;
int rows = arr.length;
int cols = arr[0].length;
// 此种方法关键点--求圈数
// 最小值除以2,向上取整
// int layers = (Math.min(rows, cols) - 1) / 2 + 1;
int layers = (int) Math.ceil
((Math.min(rows, cols)) / 2.0);
// 要打印的圈数
for (int i = 0; i < layers; i++) {
// 打印每圈
// 左至右
for (int k = i; k < cols - i; k++)
res.add(arr[i][k]);
// 右上至右下
for (int j = i + 1; j < rows - i; j++)
res.add(arr[j][cols - i - 1]);
// 注意k,j开始的下标
// 右至左
// (rows - i - 1 != i)避免重复打印第i行
for (int k = cols - i - 2; (k >= i)
&& (rows - i - 1 != i); k--)
res.add(arr[rows - i - 1][k]);
// 左下至左上
// (cols - i - 1 != i)避免重复打印第i列
for (int j = rows - i - 2; (j > i)
&& (cols - i - 1 != i); j--)
res.add(arr[j][i]);
}
return res;
}


discuss解法

 The only tricky part is that when I traverse left or up I have to check whether the row or col still exists to prevent duplicates

(往左还是往上遍历 的时候,要检查是否row和col已经存在,避免重复打印(加入if判断))

public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<Integer>();
if (matrix.length == 0) {
return res;
}
int up = 0;
int down = matrix.length - 1;
int left = 0;
int right = matrix[0].length - 1;
// 取到‘=’是因为走过的已经移动指针
while (up <= down && left <= right) {
// Traverse Right(→)
for (int j = left; j <= right; j++) {
res.add(matrix[up][j]);
}
up++;

// Traverse Down(↓)
for (int j = up; j <= down; j++) {
res.add(matrix[j][right]);
}
right--;

if (up <= down) {
// Traverse Left(←)
for (int j = right; j >= left; j--) {
res.add(matrix[down][j]);
}
}
down--;

if (left <= right) {
// Traver Up(↑)
for (int j = down; j >= up; j--) {
res.add(matrix[j][left]);
}
}
left++;
}

return res;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息