Created
January 21, 2015 07:03
-
-
Save codinfox/1b2deeb8343b2525b9dc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
private: | |
void spiral_r(vector<vector<int> > const& matrix, | |
vector<int> &result, | |
int m, int n, int start_m, int start_n) { | |
if (m<=0 || n<=0) return; | |
if (n == 1) { | |
for (int i = 0; i < m; i++) result.push_back(matrix[start_m+i][start_n]); | |
return; | |
} else if (m == 1) { | |
for (int i = 0; i < n; i++) result.push_back(matrix[start_m][start_n+i]); | |
return; | |
} | |
for (int i = 0; i < n-1; i++) { result.push_back(matrix[start_m][i + start_n]); } | |
for (int i = 0; i < m-1; i++) { result.push_back(matrix[i + start_m][n - 1 + start_n]); } | |
for (int i = n - 1; i > 0; i--) { result.push_back(matrix[m - 1 + start_m][i + start_n]); } | |
for (int i = m - 1; i > 0; i--) { result.push_back(matrix[i + start_m][start_n]); } | |
spiral_r(matrix, result, m-2, n-2, start_m+1, start_n+1); | |
} | |
public: | |
vector<int> spiralOrder(vector<vector<int> > &matrix) { | |
int m = (int)matrix.size(), n = 0; | |
if (m) n = (int)matrix[0].size(); | |
if (!n) return vector<int>(); | |
vector<int> result; | |
spiral_r(matrix, result, m, n, 0, 0); | |
return result; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment