解题思路:
采用了广度优先搜索
注意事项:
参考代码:
#include<stdio.h>
struct note {
int x;
int y;
int step;
};
int main() {
// freopen("C:\\cs.txt","r",stdin);
struct note que[100001];
int t;
scanf("%d",&t);
while(t--) {
int a[110][110] = {0},book[110][110] = {0};
int next[4][2] = {{0,1},
{1,0},
{0,-1},
{-1,0} };
int n,m,startx,starty,endx,endy,tx,ty;
scanf("%d%d",&n,&m);
getchar();
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= m; j++) {
scanf("%c",&a[i][j]);
if(a[i][j] == 'S') {
startx = i;
starty = j;
}
if(a[i][j] == 'E') {
endx = i;
endy = j;
}
}
getchar();
}
int head,tail;
head = tail = 1;
que[tail].x = startx;
que[tail].y = starty;
que[tail].step = 0;
tail++;
book[startx][starty] = 1;
int flag =0;
while(head < tail) {
for(int k = 0; k < 4; k++) { //枚举四个方向
tx = que[head].x + next[k][0];
ty = que[head].y + next[k][1];
if(tx < 1 || tx > n || //判断是否越界
ty < 1 || ty > m)
continue;
if(a[tx][ty] != '#' && book[tx][ty] == 0) {
book[tx][ty] = 1;
que[tail].x = tx;
que[tail].y = ty;
que[tail].step = que[head].step + 1;
tail++;
}
if(tx == endx && ty == endy) {
flag = 1;
break;
}
}
if(flag == 1)
break;
head++; //这个很重要哦,
}
if(head < tail)
printf("%d\n",que[tail-1].step);
else
printf("%d\n",-1);
}
return 0;
}
0.0分
0 人评分
C语言程序设计教程(第三版)课后习题10.7 (C语言代码)浏览:960 |
C语言程序设计教程(第三版)课后习题4.9 (C语言代码)浏览:377 |
wu-理财计划 (C++代码)浏览:833 |
简单的a+b (C语言代码)浏览:816 |
C语言程序设计教程(第三版)课后习题5.7 (C语言代码)浏览:633 |
字符逆序 (C语言代码)浏览:614 |
A+B for Input-Output Practice (III) (C语言代码)浏览:566 |
简单的a+b (C语言代码)浏览:574 |
1051(奇了怪了)浏览:649 |
DNA (C语言代码)浏览:740 |