【leetcode】Spiral Matrix

本文介绍了两种方法来实现矩阵的螺旋遍历,包括通过方向数组进行遍历和通过边界控制进行遍历的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spiral Matrix

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].

 
 
如果下一步会遇到访问过的节点或者越界的节点,那么就转向。
转向按照右,下,左,上
 
 1 class Solution {
 2 public:
 3     vector<int> spiralOrder(vector<vector<int> > &matrix) {
 4         int m=matrix.size();
 5         if(m==0) return vector<int>();
 6        
 7         int n=matrix[0].size();
 8        
 9         vector<int> result(m*n);
10        
11         vector<vector<bool> > visited(m,vector<bool>(n,false));
12        
13         vector<pair<int,int>> dir(4);
14         dir[0]=pair<int,int>(0,1);
15         dir[1]=pair<int,int>(1,0);
16         dir[2]=pair<int,int>(0,-1);
17         dir[3]=pair<int,int>(-1,0);
18        
19         int i,j,k,count;
20         i=j=k=count=0;
21  
22         while(1)
23         {              
24             if(count==m*n) break;
25  
26             result[count]=matrix[i][j];
27             visited[i][j]=true;
28  
29             if(i+dir[k].first>m-1||j+dir[k].second>n-1||i+dir[k].first<0||j+dir[k].second<0||visited[i+dir[k].first][j+dir[k].second])
30             {
31                 k=(++k)%4;
32             }
33  
34             i+=dir[k].first;
35             j+=dir[k].second;
36            
37             count++;
38         }
39        
40         return result;
41     }
42 };

 

 
 
另外一种方法:
 
 1 class Solution {
 2 public:
 3     vector<int> spiralOrder(vector<vector<int> > &matrix) {
 4         int m=matrix.size();
 5         if(m==0) return vector<int>();
 6        
 7         int n=matrix[0].size();
 8        
 9         vector<int> result;
10        
11        
12         int x1=0;
13         int y1=0;
14         int x2=m-1;
15         int y2=n-1;
16        
17        
18         while(1)
19         {
20            
21             for(int j=y1;j<=y2;j++) result.push_back(matrix[x1][j]);
22             x1++;
23            
24            
25             for(int i=x1;i<=x2;i++) result.push_back(matrix[i][y2]);
26             y2--;
27            
28            
29             if(x2+1!=x1)
30                 for(int j=y2;j>=y1;j--) result.push_back(matrix[x2][j]);
31             x2--;
32            
33             if(y1!=y2+1)
34                 for(int i=x2;i>=x1;i--) result.push_back(matrix[i][y1]);
35  
36             y1++;
37            
38             if(result.size()==m*n) break;
39         }
40        
41         return result;
42     }
43  
44 };

 

转载于:https://www.cnblogs.com/reachteam/p/4209678.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值