Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
Example:
Given n = 3,
You should return the following matrix:
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ] #include <iostream>
using namespace std;
int main()
{
int n = 4;
int **mat = new int*[n];
for(int i = 0 ; i < n; i++)
mat[i] = new int[n];
int dir = 0;
int k = 1;
int top = 0, bottom = n - 1, left = 0, right = n - 1;
while(top <= bottom && left <= right){
if(dir == 0){
for(int i = left; i <= right; i++){
mat[top][i] = k++;
}
top++;
dir = 1;
}
else if(dir == 1){
for(int i = top; i <= bottom; i++){
mat[i][right] = k++;
}
right--;
dir = 2;
}
else if(dir == 2){
for(int i = right; i >= left; i--){
mat[bottom][i] = k++;
}
bottom--;
dir = 3;
}else{
for(int i = bottom; i >= top; i--){
mat[i][left] = k++;
}
left++;
dir = 0;
}
}
for(int i = 0 ; i < n; i++){
for(int j = 0; j < n; j++){
cout << mat[i][j] << " ";
}
cout << endl;
}
return 0;
}
0 comments:
Post a Comment