1. 程式人生 > 其它 >2020-12-13 54. Spiral Matrix

2020-12-13 54. Spiral Matrix

技術標籤:LeetcodeArray

54. Spiral Matrix

Difficulty: Medium

Related Topics: Array

Given an m x n matrix, return all elements of the matrix in spiral order.

Example 1:

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片儲存下來直接上傳(img-SY0KckVf-1607852674083)(https://assets.leetcode.com/uploads/2020/11/13/spiral1.jpg)]

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]

Example 2:

Input: matrix = [[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]

Constraints:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 10
  • -100 <= matrix[i][j] <= 100

Solution

Key: When encountering a matrix, there are commonly some tips to think of
  1. a seen matrix to note if a node has been visited: this is good so that the condition of the loop does not required to be iterated.
  2. iterating through different layers, but needs to change the condition of the border of the layers when the outer loop goes for one round.

Language: Java

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        int count = matrix.length * matrix[0].length - 1;
        int i =
0, j = 0; List<Integer> result = new ArrayList<>(); result.add(matrix[0][0]); int layer = 0; while (count > 0) { while (count > 0 && j < matrix[0].length - 1 - layer) { j++; result.add(matrix[i][j]); count--; } while (count > 0 && i < matrix.length - 1 - layer) { i++; result.add(matrix[i][j]); count--; } while (count > 0 && j > 0 + layer) { j--; result.add(matrix[i][j]); count--; } while (count > 0 && i > layer + 1) { i--; result.add(matrix[i][j]); count--; } layer++; } return result; } }