解题感悟:
类似求最短路径的问题,都使用BFS;
#include<stdio.h>
#include<string.h>
int map[5][5]={0};
int list[1000]={0};
int temp[1000]={0};
typedef struct node{
int x,y,next;
}Node;
int mark[25];
Node node[25];
void bfs(int num);
int main(void){
int x,y;
int i,j,k;
memset(node,0,sizeof(node));
memset(mark,0,sizeof(mark));
node[24].x = node[24].y = 4;
for(i=0;i<5;++i)
for(j=0;j<5;++j){
scanf("%d",&map[i][j]);
node[i*5+j].x = i;
node[i*5+j].y = j;
}
list[0] = 24;
mark[24] = 1;
bfs(1);
for(i=0;;){
printf("(%d, %d)\n",node[i].x,node[i].y);
i = node[i].next;
if(i == 0) break;
}
return 0;
}
void bfs(int num){
int x,y,i,j,k,count,state=1;
int up,down,left,right;
while(state){
for(k=0,count=0;k<num;++k){
//得到下一组list
x = list[k] / 5;
y = list[k] % 5;
if(x==0 && y==0){
state=0;
break;
}
up = (x-1) * 5 + y;
down = (x+1) * 5 + y;
left = x * 5 + y - 1;
right = x * 5 + y + 1;
if(x>0 && map[x-1][y] == 0 && !mark[up]) {
temp[count++] = up;
mark[up]=1;
node[temp[count-1]].next = list[k];
}
if(x<4 && map[x+1][y]==0 && !mark[down]){
temp[count++] = down;
mark[down]=1;
node[temp[count-1]].next = list[k];
}
if(y>0 && map[x][y-1]==0 && !mark[left]){
temp[count++] = left;
mark[left]=1;
node[temp[count-1]].next = list[k];
}
if(y<4 && map[x][y+1]==0 && !mark[right]){
temp[count++] = right;
mark[right]=1;
node[temp[count-1]].next = list[k];
}
}
if(state)
for(i=0,num = count;i<count;++i){
list[i]=temp[i];
}
}
}