点击(此处)折叠或打开
- #include <stdio.h>
- #include <stdlib.h>
- #define M 12
- #define N 16
- #define MAXSIZE 100
- // data initiation
- int m[M][N] = {{0,1,0,0,0,1,1,0,0,0,1,1,1,1,1},
- {1,0,0,0,1,1,0,1,1,1,0,0,1,1,1},
- {0,1,1,0,0,0,0,1,1,1,1,0,0,1,1},
- {1,1,0,1,1,1,1,0,1,1,0,1,1,0,0},
- {1,1,0,1,0,0,1,0,1,1,1,1,1,1,1},
- {0,0,1,1,0,1,1,1,0,1,0,0,1,0,1},
- {0,0,1,1,0,1,1,1,0,1,0,0,1,0,1},
- {0,1,1,1,1,0,0,1,1,1,1,1,1,1,1},
- {0,0,1,1,0,1,1,0,1,1,1,1,1,0,1},
- {1,1,0,0,0,1,1,0,1,1,0,0,0,0,0},
- {0,0,1,1,1,1,1,0,0,0,1,1,1,1,0},
- {0,1,0,0,1,1,1,1,1,0,1,1,1,1,0}};
- typedef struct {
- int x,y;
- int value;
- int footprint;
- int di;
- } Cell;
- Cell mig[M][N];
- void datainit() {
- int i,j;
- Cell c;
- for (i=0;i<M;i++)
- for (j=0;j<N;j++) {
- c.x = i;
- c.y = j;
- c.value = m[i][j];
- c.di = 0;
- c.footprint = 0;
- mig[i][j] = c;
- }
- }
- // a stack
- typedef Cell eletype;
- typedef struct {
- int top;
- eletype *stack[MAXSIZE];
- } mystack;
- //mystack *ms=(mystack *)malloc(sizeof(int)*100);
- void push(mystack *s, eletype *e) {
- if (s->top>=MAXSIZE-1) { printf("mystack overflow!"); }
- else {
- ++s->top;
- s->stack[s->top]=e;
- }
- }
- void pop(mystack *s) {
- if (s->top<0) { printf("mystack empty"); }
- else {s->top--;}
- }
- int isempty(mystack *s) {
- if (s->top<0) return 1;
- else return 0;
- }
- void datainit(void);
- void push(mystack *s, eletype *e);
- void pop(mystack *s);
- int isempty(mystack *s);
- /*
- int main() {
- datainit();
- int i,j;
- for(i=0;i<M;i++) {for(j=0;j<N;j++) printf("%d",mig[i][j].value); printf("\n");}
- mystack ms;
- (&ms)->top=-1;
- push(&ms,mig[0][0]);
- push(&ms,mig[0][1]);
- printf(" %d ",(&ms)->top);
- int k; for(k=(&ms)->top;k>=0;k--) printf("stack:%d-%d\n",(&ms)->stack[k].x,(&ms)->stack[k].y);
- eletype *curele;
- curele = &mig[0][0]; curele->di++;
- printf(" %d %d\n",curele->di,(&mig[0][0])->di);
- return 0;
- }*/
- void main() {
- datainit();
- mystack ms;
- (&ms)->top=0;
- mig[0][0].footprint=1;
- (&ms)->stack[0]=&mig[0][0];
- eletype *curele;
- while (!isempty(&ms)) {
- curele = (&ms)->stack[(&ms)->top];
- if (curele->x==M-1 && curele->y==N-1) {
- printf("ok! GOt an solution.\n");
- int k;
- for (k=0;k<=ms.top;k++) printf("%d %d\n",(ms.stack[k])->x, (ms.stack[k])->y);
- break;
- }
- if (curele->di<8) {
- int i,j;
- switch(curele->di) {
- case 0: i=0;j=1;break;
- case 1: i=1;j=1;break;
- case 2: i=1,j=0;break;
- case 3: i=1;j=-1;break;
- case 4: i=0;j=-1;break;
- case 5: i=-1;j=-1;break;
- case 6: i=-1,j=0;break;
- case 7: i=-1;j=1;break;
- default: i=0;j=0;
- }
- int nx=curele->x+i;
- int ny=curele->y+j;
- curele->di++;
- eletype *nextele;
- if (nx>=0 && nx<M && ny>0 && ny<N) {
- nextele=&mig[nx][ny];
- if (nextele->value==0 && nextele->footprint==0) {nextele->footprint=1; push(&ms,nextele);}
- }
- }
- else pop(&ms);
- }
- }