Posted in 面试题 onFebruary 20, 2012
比如 N = 3,打印:
1 2 3
8 9 4
7 6 5
N = 4,打印:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
1 #define N 15
int s[N][N];
void main()
{
int k = 0, i = 0, j = 0;
int a = 1;
for( ; k {
while( j while( i while( j > k-1 ) s[i][j--] = a++; i–; j++;
while( i > k ) s[i--][j] = a++; i++; j++;
}
for( i = 0; i {
for( j = 0; j cout cout }
}
2 define MAX_N 100
int matrix[MAX_N][MAX_N];
/*
*(x,y):第一个元素的坐标
* start:第一个元素的值
* n:矩阵的大小
*/
void SetMatrix(int x, int y, int start, int n) {
int i, j;
if (n return;
if (n == 1) { //矩阵大小为1时
matrix[x][y] = start;
return;
}
for (i = x; i matrix[y][i] = start++;
for (j = y; j matrix[j][x+n-1] = start++;
for (i = x+n-1; i > x; i–) //底部
matrix[y+n-1][i] = start++;
for (j = y+n-1; j > y; j–) //左部
matrix[j][x] = start++;
SetMatrix(x+1, y+1, start, n-2); //递归
}
void main() {
int i, j;
int n;
scanf(“%d”, &n);
SetMatrix(0, 0, 1, n);
//打印螺旋矩阵
for(i = 0; i for (j = 0; j printf(“%4d”, matrix[i][j]);
printf(“\n”);
}
}
1 2 3
8 9 4
7 6 5
N = 4,打印:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
1 #define N 15
int s[N][N];
void main()
{
int k = 0, i = 0, j = 0;
int a = 1;
for( ; k {
while( j while( i while( j > k-1 ) s[i][j--] = a++; i–; j++;
while( i > k ) s[i--][j] = a++; i++; j++;
}
for( i = 0; i {
for( j = 0; j cout cout }
}
2 define MAX_N 100
int matrix[MAX_N][MAX_N];
/*
*(x,y):第一个元素的坐标
* start:第一个元素的值
* n:矩阵的大小
*/
void SetMatrix(int x, int y, int start, int n) {
int i, j;
if (n return;
if (n == 1) { //矩阵大小为1时
matrix[x][y] = start;
return;
}
for (i = x; i matrix[y][i] = start++;
for (j = y; j matrix[j][x+n-1] = start++;
for (i = x+n-1; i > x; i–) //底部
matrix[y+n-1][i] = start++;
for (j = y+n-1; j > y; j–) //左部
matrix[j][x] = start++;
SetMatrix(x+1, y+1, start, n-2); //递归
}
void main() {
int i, j;
int n;
scanf(“%d”, &n);
SetMatrix(0, 0, 1, n);
//打印螺旋矩阵
for(i = 0; i for (j = 0; j printf(“%4d”, matrix[i][j]);
printf(“\n”);
}
}
输入N,打印N*N矩阵
声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Tags in this post...
Reply on: @reply_date@
@reply_contents@