#include <iostream.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <math.h> #include <stdio.h> typedef struct Point { int x; int y; }Point; /*typedef struct Stack { Point Array[100]; int length; }Stack;*/ void fun(int (*a)[10],int i,int j,int m,int& flag) { if(i<0||j<0||i>=m||j>=m||a[i][j]!=1||flag) { return; } a[i][j]=2; if(i==9&&j==9) { flag=1; return; } fun(a,i-1,j,m,flag); fun(a,i+1,j,m,flag); fun(a,i,j-1,m,flag); fun(a,i,j+1,m,flag); if(flag) {a[i][j]=3;return;} } typedef struct PointAddr { int x; int y; int orition; }PointAddr; typedef struct Stack { PointAddr addr[100]; int length; }Stack; void Push(Stack& stack,int i,int j,int (*a)[10],int m) { if(i<0||j<0||i>=m||j>=m||a[i][j]!=1) return; PointAddr temp; temp.x=i;temp.y=j;temp.orition=0; stack.addr[stack.length]=temp; stack.length++; a[i][j]=2; } PointAddr Pop(Stack& stack) { PointAddr temp=stack.addr[stack.length-1]; stack.length--; return temp; } PointAddr GetHead(Stack& stack) { return stack.addr[stack.length-1]; } void main() { srand((unsigned)time(NULL)); int map[10][10]; int flag=0; while(!flag) { for (int i=0;i<10;i++) { for (int j=0;j<10;j++) { map[i][j]=rand()%2; } } fun(map,0,0,10,flag); } for (int i=0;i<10;i++) { for (int j=0;j<10;j++) { if(map[i][j]>0) map[i][j]=1; cout<<map[i][j]<<" "; } cout<<endl; } cout<<endl; Stack stack; stack.length=0;//栈为空 Push(stack,0,0,map,10); Stack temp1; temp1.length=100; while (stack.length>0) { PointAddr temp=GetHead(stack); if (temp.x==9&&temp.y==9) { if (temp1.length>stack.length) { temp1=stack; } map[temp.x][temp.y]=1; Pop(stack); continue; } switch(temp.orition) { case 0: { stack.addr[stack.length-1].orition++; Push(stack,temp.x+1,temp.y,map,10); } break; case 1: { stack.addr[stack.length-1].orition++; Push(stack,temp.x,temp.y+1,map,10); } break; case 2: { stack.addr[stack.length-1].orition++; Push(stack,temp.x-1,temp.y,map,10); } break; case 3: { stack.addr[stack.length-1].orition++; Push(stack,temp.x,temp.y-1,map,10); } break; case 4: { map[temp.x][temp.y]=1; Pop(stack); } break; } } cout<<temp1.length<<endl; for (i=0;i<temp1.length;i++) { cout<<temp1.addr[i].x<<","<<temp1.addr[i].y<<endl; } }