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]
.
原题链接:https://oj.leetcode.com/problems/spiral-matrix/
向右螺旋式遍历。
public class SpiralMatrix { public List<Integer> spiralOrder(int[][] matrix) { if (matrix.length == 0) return null; List<Integer> list = new ArrayList<Integer>(); int l = 0, r = matrix[0].length - 1; int u = 0, d = matrix.length - 1; while (l <= r && u <= d) { for (int i = l; i <= r; i++) list.add(matrix[u][i]); u++; if (u > d) continue; for (int i = u; i <= d; i++) list.add(matrix[i][r]); r--; if (l > r) continue; for (int i = r; i >= l; i--) list.add(matrix[d][i]); d--; if (u > d) continue; for (int i = d; i >= u; i--) list.add(matrix[i][l]); l++; } return list; } }
时间: 2024-10-11 23:20:59