LeetCode *** 54. Spiral Matrix

来源:互联网 发布:windows ping端口命令 编辑:程序博客网 时间:2024/04/29 22:20

题目:

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


分析:

模拟。


代码:

class Solution {public:    vector<int> spiralOrder(vector<vector<int>>& matrix) {        vector<int> res;                if(matrix.size()<1)return res;                int indexi=0,indexj=-1;            int n=matrix.size();        int m=matrix[0].size();        int size=m*n;                char direction='r';        for(int i=0;i<size;++i){            switch(direction){                case 'r':                    if((indexj+1)<m&&matrix[indexi][indexj+1]!=0){                        indexj++;                    }else{                        indexi++;                        direction='d';                    }                break;                case 'l':                    if((indexj-1>=0)&&matrix[indexi][indexj-1]!=0){                        indexj--;                    }else{                        indexi--;                        direction='u';                    }                break;                case 'd':                    if((indexi+1<n)&&matrix[indexi+1][indexj]!=0){                        indexi++;                    }else{                        indexj--;                        direction='l';                    }                break;                case 'u':                    if((indexi-1>=0)&&matrix[indexi-1][indexj]!=0){                        indexi--;                    }else{                        indexj++;                        direction='r';                    }                break;            }            res.push_back(matrix[indexi][indexj]);            matrix[indexi][indexj]=0;        }        return res;            }};

0 0
原创粉丝点击