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].
The first thing I thought about was recursion: scan the outer ring and narrow the matrix, then recursively call the internal matrix to complete the scan of the whole matrix.
The specific process for scanning the outer ring and shrinking the matrix is to first scan the first line, remove the first line after scanning, scan the last column, remove the last column while scanning the last line, reverse scan the last line, scan the first column, and sweep out the first column. When the scan completes, the matrix becomes smaller, and the recursive call continues to scan the smaller matrix until all the elements are scanned.
Based on the above ideas, my C + + code is implemented as follows:
vector<int>Spiralorder ( vector<vector<int> >&matrix) { vector<int>Resultif(Matrix.empty ())returnResult//Scan the first rowresult = matrix[0]; Matrix.erase (Matrix.begin ());if(Matrix.empty ())returnResult//Scan the last col intColidx = matrix[0].size ()-1; for(inti =0; I < matrix.size (); ++i) {result.push_back (matrix[i][colidx]); Matrix[i].erase (Matrix[i].begin () + colidx); }if(matrix[0].empty ())returnResult//Scan the last rowResult.insert (Result.end (), Matrix.back (). Rbegin (), Matrix.back (). rend ()); Matrix.erase (Matrix.end ()-1);if(Matrix.empty ())returnResult//Scan the first col for(inti = matrix.size ()-1; I >=0; I.) {Result.push_back (matrix[i][0]); Matrix[i].erase (Matrix[i].begin ()); }if(matrix[0].empty ())returnResult//Scan the inner matrix vector<int>Inner = spiralorder (matrix); Result.insert (Result.end (), Inner.begin (), Inner.end ());returnResult;}
Later in the discuss stroll around, found that the problem in fact with the iterative solution will be better, because the iteration does not need to reduce the matrix, directly with 4 variables to scan the top of the row, the right scan to which column, the bottom scan to which row, the left scan to which column, and then each iteration to complete a loop scan. Specific implementation can refer to here.
Leetcode[array]: Spiral Matrix