首页 > 代码库 > leetcode. Spiral Matrix

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

用left, top, right, bottom记录边界条件。

 1 vector<int> spiralOrder(vector<vector<int> > &matrix)  2     { 3         vector<int> ret; 4         int m = matrix.size(); 5         if (m <= 0) 6             return ret; 7         int n = matrix[0].size(), i = 0, j = 0; 8         int left = 0, right = n - 1, top = 0, bottom = m - 1; 9         10         while (true)11         {12             i = top, j = left;13             while (j <= right)14                 ret.push_back(matrix[i][j++]);15             if (++top > bottom) break;16             17             i = top, j = right;18             while(i <= bottom)19                 ret.push_back(matrix[i++][j]);20             if (--right < left) break;21             22             i = bottom, j = right;23             while (j >= left)24                 ret.push_back(matrix[i][j--]);25             if (--bottom < top) break;26             27             i = bottom, j = left;28             while (i >= top)29                 ret.push_back(matrix[i--][j]);30             if (++left > right) break;31         }32         33         return ret;34     }

 

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example,
Given n = 3,

You should return the following matrix:

[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]]
 1 vector<vector<int> > generateMatrix(int n)  2     { 3         vector<vector<int> > matrix; 4         if (n <= 0) 5             return matrix; 6         int left = 0, right = n - 1, top = 0, bottom = n - 1, i, j, k = 1; 7         vector<int> line(n); 8         for (i = 0; i < n; i++) 9             matrix.push_back(line);10         while (true)11         {12             i = top, j = left;13             while (j <= right)14                 matrix[i][j++] = k++;15             if (++top > bottom) break;16             17             i = top, j = right;18             while(i <= bottom)19                 matrix[i++][j] = k++;20             if (--right < left) break;21             22             i = bottom, j = right;23             while (j >= left)24                 matrix[i][j--] = k++;25             if (--bottom < top) break;26             27             i = bottom, j = left;28             while (i >= top)29                 matrix[i--][j] = k++;30             if (++left > right) break;31         }32         33         return matrix;34     }

 

leetcode. Spiral Matrix