页码40页
因为填数字只有一个顺序就是先 下 - 左 - 上 - 右 -下 。。。
所以写了四个函数代表四种步骤 执行 下 这个函数 跳出条件有两种 一种是撞墙 另外一种是
撞到自己走过的路 跳出后就执行下一个步骤 另外要注意的是 下 和 右 这两个步骤 需要 传入 参数 n
它们的墙是参数 n
1 #include <iostream> 2 #include <cstdio> 3 #include <cmath> 4 #include <cstring> 5 #include <cstdlib> 6 7 using namespace std; 8 9 int a[10][10] = {0}; 10 int i = 1; 11 int x, y; 12 int step1 (int n) 13 { 14 while(y+1 < n && !a[x][y+1] ) 15 { 16 y = y + 1; 17 i++; 18 a[x][y] = i; 19 } 20 return 1; 21 } 22 int step2 () 23 { 24 while(x-1 >= 0 && !a[x-1][y] ) 25 { 26 x = x - 1; 27 i++; 28 a[x][y] = i; 29 } 30 return 1; 31 } 32 int step3 () 33 { 34 while( y-1 >= 0 && !a[x][y-1] ) 35 { 36 y = y - 1; 37 i++; 38 a[x][y] = i; 39 } 40 return 1; 41 } 42 int step4 (int n) 43 { 44 while(x + 1 < n && !a[x+1][y] ) 45 { 46 x = x + 1; 47 i++; 48 a[x][y] = i; 49 } 50 return 1; 51 } 52 53 int main() 54 { 55 int n, j, k; 56 scanf("%d",&n); 57 x = n-1; 58 y = 0; 59 a[x][y] = 1; 60 //printf("x = %d , y = %d , i = %d \n",x,y,i); 61 for(i=1;i<n*n;) 62 { 63 step1(n); 64 //printf("x = %d , y = %d , i = %d \n",x,y,i); 65 step2(); 66 step3(); 67 step4(n); 68 } 69 for(j=0;j<n;j++) 70 { 71 for(k=0;k<n;k++) 72 { 73 printf("%3d",a[k][j]); 74 } 75 printf("\n"); 76 } 77 return 0; 78 }