Monday, April 14, 2014

LeetCode: Spiral Matrix I && II


Spiral Matrix 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].

这个问题难点在外层for循环的结束条件. Have to pay attention to Line 27 and Line 31 to break the outer loop so as to deal with matrix like [[1,11],[2, 12],[3, 13],[4, 14],[5, 15],[6, 16],[7, 17]]. In addition, It doesn't affect the result if commenting out line 10 to line 14, but line 16 to line 21 are necessary

vector<int> spiralOrder(vector<vector<int> > &matrix) {
int row = matrix.size();
int column;
vector<int> spiral;
if(row>0)
column = matrix[0].size();
else return spiral;
if(row == 1){
for(int l=0; l<column; l++)
spiral.push_back(matrix[0][l]);
return spiral;
}
if(column == 1){
for(int l=0; l<row; l++)
spiral.push_back(matrix[l][0]);
return spiral;
}
int i, j, k, m, n;
for(i=0; i<(row+1)/2; i++){
if(i>=column-i) break;
for(j=i; j<column-i; j++)
spiral.push_back(matrix[i][j]);
if(i+1 >= row-i) break;
for(k=i+1; k<row-i; k++)
spiral.push_back(matrix[k][j-1]);
for(m=j-2; m>=i; m--)
spiral.push_back(matrix[k-1][m]);
for(n=k-2; n>i; n--)
spiral.push_back(matrix[n][i]);
}
return spiral;
}
view raw gistfile1.cpp hosted with ❤ by GitHub




Spiral Matrix II
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 ]
]



Not difficult in the algorithm, but need to be carefully about the index.
Had a little problem with the two dimensional vector. In order to access it with [][], matrix has to be initialized. Vecter<int> v(n) is to set the length of v to n.




vector<vector<int> > generateMatrix(int n) {
vector<vector<int>> matrix;
if(n==0) return matrix;
if(n==1){
vector<int> v;
v.push_back(n);
matrix.push_back(v);
return matrix;
}
for(int i=0; i<n; i++){
vector<int> v(n);
matrix.push_back(v);
}
int i, j, k, m, l;
int num=1;
for(i=0; i<(n+1)/2; i++){
for(j=i; j<n-i; j++)
matrix[i][j]=num++;
for(k=i+1; k<n-i; k++)
matrix[k][j-1]=num++;
for(m=j-2; m>=i; m--)
matrix[k-1][m]=num++;
for(l=k-2; l>i; l--)
matrix[l][i]=num++;
}
return matrix;
}
view raw gistfile1.cpp hosted with ❤ by GitHub

No comments:

Post a Comment