[LeetCode] Spiral Matrix

本文介绍了一种使用深度优先搜索(DFS)策略按螺旋顺序遍历矩阵的方法。通过维护一个额外的布尔矩阵来跟踪已访问元素,确保每个元素仅被访问一次。此方法的时间复杂度为O(n*m),空间复杂度也为O(n*m)。

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example,
Given the following matrix:

[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]

You should return [1,2,3,6,9,8,7,4,5].

开一个数组用来保存,之前这个单元是否被使用过,并配合边界判断,DFS,最后得出结果。空间复杂度O(n*m),时间O(n*m)

 1 class Solution {
 2 private:
 3     int step[4][2];
 4     vector<int> ret;
 5     bool canUse[100][100];
 6 public:
 7     void dfs(vector<vector<int> > &matrix, int direct, int x, int y)
 8     {
 9         for(int i = 0; i < 4; i++)
10         {
11             int j = (direct + i) % 4;
12             int tx = x + step[j][0];
13             int ty = y + step[j][1];
14             if (0 <= tx && tx < matrix.size() && 0 <= ty && ty < matrix[0].size() && canUse[tx][ty])
15             {
16                 canUse[tx][ty] = false;
17                 ret.push_back(matrix[tx][ty]);                
18                 dfs(matrix, j, tx, ty);               
19             }            
20         }
21     }
22     
23     vector<int> spiralOrder(vector<vector<int> > &matrix) {
24         // Start typing your C/C++ solution below
25         // DO NOT write int main() function
26         step[0][0] = 0;
27         step[0][1] = 1;
28         step[1][0] = 1;
29         step[1][1] = 0;
30         step[2][0] = 0;
31         step[2][1] = -1;
32         step[3][0] = -1;
33         step[3][1] = 0;
34         ret.clear();
35         memset(canUse, true, sizeof(canUse));
36         dfs(matrix, 0, 0, -1);
37         
38         return ret;
39     }
40 };
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值