[LeetCode] Spiral Matrix, leetcodespiral
The meaning of this question is relatively simple, that is, the data of the spiral output array ,[
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
You shoshould return [1, 2, 3, 6, 9, 8, 7, 4, 5].
My own solution is direct, that is, gradually recursion from the outermost layer to the inner layer. This method does not require additional storage space, but the boundary control is cumbersome. The Code is as follows:
Public List <Integer> spiralOrder (int [] [] matrix) {List <Integer> rs = new partition List <Integer> (); int m, n; // row and column if (matrix = null | matrix. length = 0) return rs; else {m = matrix. length; n = matrix [0]. length; getSpiralData (matrix, 0, 0, m, n, rs);} return rs ;} /*** obtain data cyclically * @ param matrix data matrix * @ param startX start position * @ param startY * @ param maxM max row * @ param maxN max column * @ param rs result list */public void getSpiralData (int [] [] matrix, int startX, int startY, int maxM, int maxN, List <Integer> rs) {if (maxM <= 0 | maxN <= 0) {return ;} else {int x = startX, y = startY; if (maxM = 1) {while (y <startY + maxN) {rs. add (matrix [x] [y]); y ++;} return ;}if (maxN = 1) {while (x <startX + maxM) {rs. add (matrix [x] [y]); x ++;} return ;}while (y <= startY + maxN-1) {rs. add (matrix [x] [y]); y ++;} x = x + 1; y = startY + maxN-1; while (x <= startX + maxM-1) {rs. add (matrix [x] [y]); x ++;} y = Y-1; x = startX + maxM-1; while (y> = startY) {rs. add (matrix [x] [y]); y --;} x = X-1; y = startY; while (x> startX) {rs. add (matrix [x] [y]); x --;} getSpiralData (matrix, startX + 1, startY + 1, maxM-2, maxN-2, rs );}}
In addition, it is quite intuitive to see other solutions on the Internet. By controlling the direction of each step, you can use an additional array to save whether access has been made. The Code is as follows:
Http://www.cnblogs.com/remlostime/archive/2012/11/18/2775708.html
class Solution {private: int step[4][2]; vector<int> ret; bool canUse[100][100];public: void dfs(vector<vector<int> > &matrix, int direct, int x, int y) { for(int i = 0; i < 4; i++) { int j = (direct + i) % 4; int tx = x + step[j][0]; int ty = y + step[j][1]; if (0 <= tx && tx < matrix.size() && 0 <= ty && ty < matrix[0].size() && canUse[tx][ty]) { canUse[tx][ty] = false; ret.push_back(matrix[tx][ty]); dfs(matrix, j, tx, ty); } } } vector<int> spiralOrder(vector<vector<int> > &matrix) { // Start typing your C/C++ solution below // DO NOT write int main() function step[0][0] = 0; step[0][1] = 1; step[1][0] = 1; step[1][1] = 0; step[2][0] = 0; step[2][1] = -1; step[3][0] = -1; step[3][1] = 0; ret.clear(); memset(canUse, true, sizeof(canUse)); dfs(matrix, 0, 0, -1); return ret; }};