标签:leetcode matrix spiral matrix
题目链接:https://oj.leetcode.com/problems/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]
.
解题思路:运用了verilog状态机的思想,定义了一个state,进行状态的判断;状态1,从左到右,状态2,从上到下,状态3,从右到左,状态4,从下 到 上。(注意下,容器为空时的判断。)
<pre name="code" class="cpp"> int m = matrix.size(); vector<int> answers; if(m == 0) return answers ;
不要写成,下面这种情况,会报错的。
int m = matrix.size(); int n = matrix[0].size(); vector<int> answers; if(m == 0) return answers ;
class Solution { public: vector<int> spiralOrder(vector<vector<int> > &matrix) { int m = matrix.size(); vector<int> answers; if(m == 0) return answers ; int n = matrix[0].size(); int s[m][n]; for(size_t i = 0; i != m; i++) for(size_t j = 0; j != n; j++) s[i][j] = 0; int state = 1; int k = 0; int l = 0; int num = 0; while(num < m*n ) { if(state == 1) { //left to right if(s[k][l] != 1 && l != n) { answers.push_back(matrix[k][l]); num ++; s[k][l] = 1; l++; } else { l--; k++; state=2; } } else if(state == 2) { //top to down if(s[k][l] != 1 && k != m) { answers.push_back(matrix[k][l]); num ++; s[k][l] = 1; k++; } else { k--; l--; state =3; } } else if(state == 3) { //right to left if(s[k][l] != 1 && l != -1) { answers.push_back(matrix[k][l]); num ++; s[k][l] = 1; l--; } else { l++; k--; state =4; } } else if(state == 4) { //down to top if(s[k][l] != 1 && k != 0) { answers.push_back(matrix[k][l]); num ++; s[k][l] = 1; k--; } else { k++; l++; state =1; } } } return answers; } };
标签:leetcode matrix spiral matrix
原文地址:http://blog.csdn.net/vanish_dust/article/details/42985599