leetcode 54. Spiral Matrix | 54. 螺旋矩阵(Java)
生活随笔
收集整理的這篇文章主要介紹了
leetcode 54. Spiral Matrix | 54. 螺旋矩阵(Java)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目
https://leetcode.com/problems/spiral-matrix/
題解
類似于狀態機的思路,設定一個 padding,走一圈之后,padding+1 。用 長寬 - padding 確定邊界,一旦到達邊界,則改變方向。用 count 記錄已經走過的格子數量,當走過格子數量=所有格子之后,算法結束。
class Solution {public List<Integer> spiralOrder(int[][] matrix) {List<Integer> list = new ArrayList<>();int count = 0;int y = matrix.length;int x = matrix[0].length;int i = 0;int j = 0;int padding = 0;int direct = 0;// 0=right 1=down 2=left 3=upwhile (count < y * x) {list.add(matrix[i][j]);count++;switch (direct) {case 0 -> {if (j < x - padding - 1) {j++;} else {direct = 1;i++;}}case 1 -> {if (i < y - padding - 1) {i++;} else {direct = 2;j--;}}case 2 -> {if (j > padding) {j--;} else {direct = 3;i--;}}case 3 -> {if (i > padding + 1) {i--;} else {direct = 0;padding++;j++;}}}}return list;} }總結
以上是生活随笔為你收集整理的leetcode 54. Spiral Matrix | 54. 螺旋矩阵(Java)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode 304. Range
- 下一篇: leetcode 1338. Reduc