解题思路:
采用了广度优先搜索
注意事项:
参考代码:
#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 人评分
WU-整除问题 (C++代码)浏览:648 |
C语言训练-自由落体问题 (C语言代码)浏览:650 |
模拟计算器 (C++代码)浏览:885 |
2003年秋浙江省计算机等级考试二级C 编程题(1) (C语言代码)浏览:721 |
简单的a+b (C语言代码)浏览:1024 |
C语言程序设计教程(第三版)课后习题8.4 (C语言代码)浏览:585 |
小O的乘积 (C++代码)浏览:796 |
2003年秋浙江省计算机等级考试二级C 编程题(2) (C语言代码)浏览:748 |
C语言程序设计教程(第三版)课后习题1.5 (C语言代码)浏览:477 |
1415题求解浏览:681 |