[LeetCode]-Spiral Matrix I&II 螺旋矩陣

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

     如果從上下左右四個方向依次訪問直到遇到“已經訪問過或邊界”節點,順序切換訪問方向即可。本題測試用例中會有matrix[0][n] 這種用例,會一直出現runtime error並且不提示信息,所以一定要判定matrix是否爲空。

   

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int> > &matrix) {
        const int m=matrix.size();
        if(m==0)return vector<int>();
        const int n=matrix[0].size();
        if(n==0)return vector<int>();

        vector<int> ret;
        vector<vector<int> > visited(m,vector<int>(n,0));

        int i=0,j=0;
        int flag=1;
        while(flag){
            flag=0;
            for(j;j<n && j>=0 && visited[i][j]!=1;j++){    //  向右訪問
                ret.push_back(matrix[i][j]);
                visited[i][j]=1;
                flag=1;
            }
            j--;i++;
            for(i;i<m &&i>=0 && visited[i][j]!=1;i++){   // 向下訪問
                ret.push_back(matrix[i][j]);
                visited[i][j]=1;
                flag=1;
            } 
            i--;j--;
            for(j;j<n &&j>=0 && visited[i][j]!=1;j--){   // 向左訪問
                ret.push_back(matrix[i][j]);
                visited[i][j]=1;
                flag=1;
            }
            j++;i--;
            for(i;i<m &&i>=0 && visited[i][j]!=1;i--){   // 向上訪問
                ret.push_back(matrix[i][j]);
                visited[i][j]=1;
                flag=1;
            }
            i++;j++;
        }
        return ret;
    }
    
};

Spiral Matrix II

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example,
Given n = 3,

You should return the following matrix:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]
    此題相比I,更簡單,思路一樣。

class Solution {
public:
    vector<vector<int> > generateMatrix(int n) {
       vector<vector<int> > ret(n,vector<int>(n,0));
        if(n==0) return vector<vector<int> >();

       int i=0,j=0;
       int count=1,flag=1;
       while(flag){
           flag=0;
           for(j;j<n && j>=0 && ret[i][j]==0;j++){
                ret[i][j]=count++;
                flag=1;
           }
           j--;i++;
           for(i;i<n && i>=0 && ret[i][j]==0;i++){
                ret[i][j]=count++;
                flag=1;
           }
           i--;j--;
           for(j;j<n && j>=0 && ret[i][j]==0;j--){
                ret[i][j]=count++;
                flag=1;
           }
           j++;i--;
           for(i;i<n && i>=0 && ret[i][j]==0;i--){
                ret[i][j]=count++;
                flag=1;
           }
           i++;j++;
        }
       return ret;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章