登 录
/* HELLO.C -- Hello, world */ #include "stdio.h" #include "string.h" #define SIZE 5 int main() { int a[SIZE][SIZE]; int x=0,y=SIZE-1,step=0; int i=0; memset(a,0,sizeof(a)); a[x][y]=++step; while(step<=SIZE*SIZE) { /*以下语句只是为了测试时死循环,没有功能作用*/ if(i++ == (SIZE+1)/2) break; printf("step=%d/n",step); printf("x=%d,y=%d,a=%d/n",x,y,(a[x][y] )); while(x+1<SIZE && a[x+1][y]==0) { a[++x][y]=++step; printf("x=%d,y=%d,step=%d/n",x,y,step); } while(y-1>=0 && a[x][y-1]==0) { a[x][--y]=++step; printf("x=%d,y=%d,step=%d/n",x,y,step); } while(x-1>= 0 && a[x-1][y]==0) { a[--x][y]=++step; printf("x=%d,y=%d,step=%d/n",x,y,step); } while(y+1<SIZE && a[x][y+1]==0) { a[x][++y]=++step; printf("x=%d,y=%d,step=%d/n",x,y,step); } } for(x=0;x<SIZE;x++) { for(y=0;y<SIZE;y++) { printf("%d/t",a[x][y]); } printf("/n"); } getch(); }
算法规律:
每个循环包括四个循环:向一直向下左,然后一直向左走,然后一直向上走,然后一直向右走
抱歉!评论已关闭.