首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

LeetCode Spiral Matrix:矩陣螺旋遍歷 — 邊界收縮法

     編輯:關於C++

題目描述

給定一個 m×n 矩陣(不一定是正方形),按順時針螺旋順序輸出所有元素。

範例:

輸入: [[1,2,3],[4,5,6],[7,8,9]]
輸出: [1,2,3,6,9,8,7,4,5]

解題思路

維護四個邊界:top, bottom, left, right。循環條件 left <= right && top <= bottom。每圈依序遍歷:

  1. 頂行:left → right,top++。
  2. 右欄:top → bottom,right--。
  3. 若 top <= bottom,底行:right → left,bottom--。
  4. 若 left <= right,左欄:bottom → top,left++。

條件判斷避免重複遍歷單行/單列情況。

參考代碼 (Python)

class Solution:
    def spiralOrder(self, matrix):
        if not matrix: return []
        top, bottom = 0, len(matrix) - 1
        left, right = 0, len(matrix[0]) - 1
        res = []
        while left <= right and top <= bottom:
            for i in range(left, right + 1):
                res.append(matrix[top][i])
            top += 1
            for i in range(top, bottom + 1):
                res.append(matrix[i][right])
            right -= 1
            if top <= bottom:
                for i in range(right, left - 1, -1):
                    res.append(matrix[bottom][i])
                bottom -= 1
            if left <= right:
                for i in range(bottom, top - 1, -1):
                    res.append(matrix[i][left])
                left += 1
        return res

複雜度分析

  • 時間:O(mn) —— 每個元素訪問一次。
  • 空間:O(1) 額外空間(不含輸出)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved