LeetCode--Spiral Matrix
Posted CR2014
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode--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]
.
注意:是螺旋形,不是S形!
特点:每次运动时,要么行不变,要么列不变;
代码思路很好!!!
代码:
package leetcode;
import java.util.ArrayList;
import java.util.List;
public class CorrectSpiralMatrix {
public static List<Integer> spiralOrder(int[][] matrix) {
List<Integer> list = new ArrayList<>();
if (matrix == null || matrix.length < 1) {
return list;
}
int m = matrix.length;
int n = matrix[0].length;
if (m == 1 && n == 1) {
list.add(matrix[0][0]);
return list;
}
int dir = 0;
int top = 0, right = n-1, left = 0, buttom = m-1; //对应的行数,列数应该一致;
while (top <= buttom && left <= right) { //0,1,2,3代表四个方向!
if (dir == 0) {
for (int i = left; i <= right; i++) {
list.add(matrix[top][i]);
}
top++;
}
if (dir == 1) {
for (int i = top; i <= buttom; i++) {
list.add(matrix[i][right]);
}
right--;
}
if (dir == 2) {
for (int i = right; i >= left; i--) {
list.add(matrix[buttom][i]);
}
buttom--;
}
if (dir == 3) {
for (int i = buttom; i >= top; i--) {
list.add(matrix[i][left]);
}
left++;
}
dir = (dir + 1) % 4; //更改方向!
}
return list;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[][] arr = { { 1, 2, 3 ,4,5,6}, { 7,8, 9,10,11,12 }, { 12,13,14,15,16,17 } };
Long long1 = System.currentTimeMillis();
System.out.print(spiralOrder(arr));
Long long2 = System.currentTimeMillis();
Long long3 = long2 - long1;
System.out.println("耗时" + long3 + "毫秒!");
}
}
教训:为什么不能用回溯?
以上是关于LeetCode--Spiral Matrix的主要内容,如果未能解决你的问题,请参考以下文章