Given an m x n matrix, return all elements of the matrix in spiral order.
Example 1:
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.lengthn == matrix[i].length1 <= m, n <= 10-100 <= matrix[i][j] <= 100
SOL:
解題思路我參考的是這篇:leetcode 中文 | Spiral Matrix | Microsoft 面試考題 | LeetCode 54 | Python
但因為我想用C解決這個問題,所以用 ChatGPT 來協助我(不用上網找正解真的很方便
需要注意的是當我們先向右、向下遍歷之後,已經在 while(top <= bottom && left <= right) 中,但又會改變到 top、right 的值。所以接下來在向左、向上遍歷的時候,必須要做 top<=bottom、left<=right 的確認,避免只有一行時 top>bottom,又重複拜訪。
文章標籤
全站熱搜
