最少步数
简单的bfs题目
#include <stdio.h>
#include <string.h>
int map[9][9]={
{1,1,1,1,1,1,1,1,1},
{1,0,0,1,0,0,1,0,1},
{1,0,0,1,1,0,0,0,1},
{1,0,1,0,1,1,0,1,1},
{1,0,0,0,0,1,0,0,1},
{1,1,0,1,0,1,0,0,1},
{1,1,0,1,0,1,0,0,1},
{1,1,0,1,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1}
};
int visit[9][9], k;
int pre[1000];
int dir[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
struct cam{
int x;
int y;
}list[1000];
int go(int x, int y)
{
if(0 <= x && x < 9 && 0 <= y && y < 9 && map[x][y] == 0)
return 1;
return 0;
}
int print(int x, int sum)
{
int t;
t = pre[x];
if(t != 0)
return 1 + print(t, sum);
else{
return 1;
}
}
void bfs()
{
int l;
int x1, y1, x2, y2, n;
int head, tail;
int x, y, xx, yy;
scanf("%d", &n);
while(n--){
scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
if (x1 == x2 && y1 == y2){
printf("0\n");
continue;
}
memset(visit, 0, sizeof(visit));
k = 0;
head = 0;
tail = 1;
list[0].x = x1;
list[0].y = y1;
pre[0] = -1;
while(head < tail){
x = list[head].x;
y = list[head].y;
if(x == x2 && y == y2){
l = print(head, 0);
printf("%d\n", l);
break;
}
for (int i = 0; i < 4; i++){
xx = x + dir[i][0];
yy = y + dir[i][1];
if (!visit[xx][yy] && go(xx, yy)){
visit[xx][yy] = 1;
list[tail].x = xx;
list[tail].y = yy;
pre[tail] = head;
tail++;
}
}
head++;
}
}
return;
}
int main(void)
{
bfs();
return 0;
}