Spiral Matrix

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

For example,
Given the following matrix:spa

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

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

這道打印矩陣的題之前遇到不少次,但寫代碼的時候仍是有不少種狀況沒有考慮到,致使花費挺多時間。blog

題意:給定一個m*n的矩陣,從外圍一層一層的打印出矩陣中的數據element

思路:使用兩個結點分別記錄當前還沒有訪問到的矩陣的左上角和右下角的位置,根據兩個結點的值能夠訪問到矩陣最外層的數據,而後讓兩個結點指向新的位置。it

結束條件:假設記錄矩陣訪問信息的兩個結點爲a,b.則當a.x>=b.x 或者a.y>=b.y的時候應該結束。再者能夠根據矩陣的大小信息,當m<n的時候兩個結點會在橫座標方向相遇,當m>n的時候兩個結點會在豎座標方向相遇。io

 1 struct node
 2 {
 3     int x,y;
 4     node(int _x,int _y):x(_x),y(_y){}
 5 };
 6   
 7 vector<int> spiralOrder(vector<vector<int> > &matrix) {
 8     // Start typing your C/C++ solution below
 9     // DO NOT write int main() function
10     vector<int> data;
11     int m=matrix.size();
12     if(m==0)
13         return data;
14     int n=matrix[0].size();
15     if(n==0)
16         return data;
17     node a(0,0);
18     node b(m-1,n-1);
19     int e = m < n ? m : n;
20     e = e/2;
21     while(e--){
22         for(int i=a.y;i<=b.y;i++)
23             data.push_back(matrix[a.x][i]);
24         for(int i=a.x+1;i<=b.x;i++)
25             data.push_back(matrix[i][b.y]);
26         for(int i=b.y-1;i>=a.y;i--)
27             data.push_back(matrix[b.x][i]);
28         for(int i=b.x-1;i>a.x;--i)
29             data.push_back(matrix[i][a.y]);
30         a.x++;
31         a.y++;
32         b.x--;
33         b.y--;
34     }
35         
36     if(a.x==b.x)
37     {
38         for(int i=a.y;i<=b.y;i++)
39             data.push_back(matrix[a.x][i]);
40     }else if(a.y==b.y){
41         for(int i=a.x;i<=b.x;i++)
42             data.push_back(matrix[i][a.y]);
43     }
44     return data;
45 }
相關文章
相關標籤/搜索