作者Rushia (みけねこ的鼻屎)
看板Marginalman
標題[LC] LEETCODE 54
時間Fri Jun 16 20:17:01 2023
https://leetcode.com/problems/spiral-matrix/description/
54. Spiral Matrix
給你一個用二維陣列表示的 m x n 的矩陣,返回他的所有元素(螺旋順序)。
Example 1
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:
https://assets.leetcode.com/uploads/2020/11/13/spiral.jpg
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]
思路:
1.遍歷陣列的時候不斷往某個方向前進,直到碰到邊界或碰到已經走過的地方就往下一個
方向。
Java Code:
-----------------------------------------
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<>();
int m = matrix.length;
int n = matrix[0].length;
boolean[][] visited = new boolean[m][n];
int y = 0;
int x = 0;
int[][] dirs = new int[][]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int turn = 0;
while (res.size() != m * n) {
visited[y][x] = true;
res.add(matrix[y][x]);
int newY = y + dirs[turn][0];
int newX = x + dirs[turn][1];
if (newY < 0 || newY >= m || newX < 0 || newX >= n ||
visited[newY][newX]) {
turn = (turn + 1) % 4;
newY = y + dirs[turn][0];
newX = x + dirs[turn][1];
}
y = newY;
x = newX;
}
return res;
}
}
-----------------------------------------
明天要上班 哭阿
--
https://i.imgur.com/uiFto42.jpg
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 122.100.75.86 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1686917824.A.89D.html