I. 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]
.
Analyse: four steps. Top right, right down, bottom left, left up.
Runtime: 0ms.
1 class Solution { 2 public: 3 vector<int> spiralOrder(vector<vector<int>>& matrix) { 4 int m = matrix.size(); 5 vector<int> result; 6 if(m == 0) return result; 7 8 int n = matrix[0].size(); 9 int x = 0, y = 0; 10 while(m > 0 && n > 0){ 11 if(m == 1){ 12 for(int i = 0; i < n; i++) 13 result.push_back(matrix[x][y++]); 14 break; 15 } 16 else if(n == 1){ 17 for(int j = 0; j < m; j++) 18 result.push_back(matrix[x++][y]); 19 break; 20 } 21 22 for(int i = 0; i < n - 1; i++){//top-right scan 23 result.push_back(matrix[x][y++]); 24 } 25 for(int i = 0; i < m - 1; i++){//right-down scan 26 result.push_back(matrix[x++][y]); 27 } 28 for(int i = 0; i < n - 1; i++){//bottom-left scan 29 result.push_back(matrix[x][y--]); 30 } 31 for(int i = 0; i < m - 1; i++){//left-up scan 32 result.push_back(matrix[x--][y]); 33 } 34 35 x++; 36 y++; 37 m -= 2; 38 n -= 2; 39 } 40 return result; 41 } 42 };
II. Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
Analyse: The same as 1.
Runtime: 8ms.
1 class Solution { 2 public: 3 vector<vector<int>> generateMatrix(int n) { 4 vector<vector<int> > result(n, vector<int>(n, 0)); 5 if(n == 0) return result; 6 if(n == 1){ 7 result[0][0] = 1; 8 return result; 9 } 10 11 int current = 0; 12 int x = 0, y = 0; 13 int row = n, col = n; 14 while(row > 0 && col > 0){ 15 if(row == 1){ 16 for(int i = 0; i < col; i++) 17 result[x][y++] = ++current; 18 break; 19 } 20 else if(col == 1){ 21 for(int i = 0; i < row; i++) 22 result[x++][y] = ++current; 23 break; 24 } 25 26 for(int i = 0; i < col - 1; i++){//put top-right 27 result[x][y++] = ++current; 28 } 29 for(int i = 0; i < row - 1; i++){//put top-down 30 result[x++][y] = ++current; 31 } 32 for(int i = 0; i < col - 1; i++){//put bottom-left 33 result[x][y--] = ++current; 34 } 35 for(int i = 0; i < row - 1; i++){//put bottom-up 36 result[x--][y] = ++current; 37 } 38 x++; 39 y++; 40 row -= 2; 41 col -= 2; 42 } 43 return result; 44 } 45 };