我在填写矩阵时遇到问题,如下图所示。 矩阵必须是NxN,N是偶数。
我认为最好的方法是在for
内使用两个while
。像这样:
int a=0, c=1, i, j, flag=0, map[N][N] //N with a #define
//First I input my matrix with 0.
for (i=0; i<N; i++)
for (j=0; j<N; j++)
map[i][j]=0;
//Here I fill the matrix
while(!flag){
for(j=a; j<N-a; j++){
map[i][j]=c;
c++;
}
for(i=a+1; i<N-a; i++){
map[i][j]=c;
c++;
}
for(j=N-a-1; j>=a; j--){
map[i][j]=c;
c++;
}
for(i=N-a-1; i>a+1; i--){
if(map[i][j]==0){
map[i][j]=c;
c++;
}
else if(map[i][j]!=0)
flag=1;
}
c=1;
a++;
}
问题是id不起作用......你能帮助我吗?感谢
答案 0 :(得分:2)
如果不修改大部分代码,最简单的方法如下:
#define N 4
#include<stdio.h>
int a=0, c=1, i, j, flag=0, map[N][N]; //N with a #define
main() {
//First I input my matrix with 0.
for (i=0; i<N; i++)
for (j=0; j<N; j++)
map[i][j]=0;
i=0;
//Here I fill the matrix
while(!flag){
for(j=a; j<N-a; j++){
map[i][j]=c;
c++;
}
j--;
for(i=a+1; i<N-a-1; i++){
map[i][j]=c;
c++;
}
for(j=N-a-1; j>=a; j--){
map[i][j]=c;
c++;
}
j++;
for(i=N-a-1; i>=a+1; i--){
if(map[i][j]==0){
map[i][j]=c;
c++;
}
}
if(map[i+1][j+1]!=0)
flag=1;
c=1;
a++;
i++;
}
for(i=0;i<N;i++){
for(j=0;j<N;j++){
printf("%d ",map[i][j]);
}
printf("\n");
}
}
此处N
设置为4
。所以输出如下:
1 2 3 4
12 1 2 5
11 4 3 6
10 9 8 7
答案 1 :(得分:1)
您有两类问题:
i
或j
。因此,在尝试填充矩阵时,您通常会超出界限。flag
永远不会被设置为1,因为填充矩阵后它的for循环将永远不会运行(通过纸上的代码跟踪以确切了解原因)。现在,使用for-loop边界,实际上并不需要flag
来跟踪填充矩阵的时间。考虑到这些点,您修改的代码可能如下所示:
int a=0, c=1, i, j, map[N][N] //N with a #define
// (no need to fill your matrix with zeros; your matrix will be filled when your while-loop below ends)
//Here I fill the matrix
while(a < N/2){ // <- stop filling the matrix once a == N/2
i = a; // <- set i, otherwise the for-loop below will use i=undefined on the first iteration (or i=N if you keep the zeroing code above)
for(j=a; j<N-a; j++){
map[i][j]=c;
c++;
}
j = N-a-1; // <- set j, otherwise the for-loop below will use j=N-a, which is out-of-bounds on the first iteration
for(i=a+1; i<N-a; i++){
map[i][j]=c;
c++;
}
i = N-a-1; // <- set i, otherwise the for-loop below will use i=N-a, which, again, is out-of-bounds on the first iteration
for(j=N-a-2; j>=a; j--){ // <- set j=N-a-2 instead of j=N-a-1 to avoid overwriting existing elements of the map
map[i][j]=c;
c++;
}
j = a; // <- set j, otherwise the for-loop below will use j=a-1, which is out-of-bounds on the first iteration
for(i=N-a-2; i>a+1; i--){ // <- set i=N-a-2 instead of i=N-a-1 to avoid overwriting existing elements of the map
// (no need to check if an element is 0)
map[i][j]=c;
c++;
}
c=1;
a++;
}