1.
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]
.
vector<int> spiralOrder(vector<vector<int>>& matrix) { vector<int> ans; int m = matrix.size(); if(m < 1) return ans; int n = matrix[0].size(), size = m*n, x1=0, x2=m-1, y1=0, y2=n-1, i, j, k=0; while(k < size) { for(i=y1; i<=y2; i++) { ans.push_back(matrix[x1][i]); k++; } for(i=x1+1; i<=x2; i++) { ans.push_back(matrix[i][y2]); k++; } for(i=y2-1; x2>x1 && i>=y1; i--) { ans.push_back(matrix[x2][i]); k++; } for(i=x2-1; y2>y1 && i>x1; i--) { ans.push_back(matrix[i][y1]); k++; } x1++; x2--; y1++; y2--; } return ans; }
注意:
下面和左面的边,即第三个和第四个for循环,要加条件x2>x1和y2>y1,否则会有重复元素。
2.
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 ] ]
vector<vector<int>> generateMatrix(int n) { vector<vector<int>> ans(n, vector<int>(n, 0)); int size = n*n, x1=0, x2=n-1, y1=0, y2=n-1, i, j, k=0; while(k < size) { for(i=y1; i<=y2; i++) ans[x1][i] = ++k; for(i=x1+1; i<=x2; i++) ans[i][y2] = ++k; for(i=y2-1; x2>x1 && i>=y1; i--) ans[x2][i] = ++k; for(i=x2-1; y2>y1 && i>x1; i--) ans[i][y1] = ++k; x1++; x2--; y1++; y2--; } return ans; }