题目链接:http://acm.tju.edu.cn/toj/showp2470.html
题目大意:机器人走迷宫 算出从起点出发到终点的最少步数 只能有左转 右转 前进三种选择;
思路:看到矩阵 看到最少步数 毫不犹豫BFS 另外:方向向量很重要!这道题是使我以后都喜欢上用结构体和方向向量,4个方向也好 8个方向也好 都是类似的:struct{int x,y;}ext[4]={{-1,0},{0,1},{1,0},{0,-1}};//分别代表4个方向 上下左右必须有相互之间的顺序 比如 1和2颠倒就会错误! ps:左转和右转只是方向变化 坐标并不会变化!
代码如下:
#include<iostream>#include<stdio.h>
#include<string.h>
using namespace std;
int visited[101][101][4]; //因为4个方向 所以第三个参数为4
char map[101][101];
int x,y,m,n;
struct{int x,y;}ext[4]={{-1,0},{0,1},{1,0},{0,-1}};//分别代表4个方向 上下左右必须有相互之间的顺序 比如 1和2颠倒就会错误
struct{int x,y,l,r;}q[40001]; //x y l r 分别表示 x坐标 y坐标 距起点的步数 方向
int bfs()
{
int i,j,top,xt,yt,rt;
memset(visited,0,sizeof(visited)); //以下6行为初始化顶点
top=0;
q[top].x = x;
q[top].y = y;
q[top].r = 0;
q[top].l = 0;
visited[x][y][q[top++].r]=1; //visited一定要找准是哪个点 曾经有一道BFS的题我就是这儿错了 折腾了好久
for(i=0;i<top;i++) //BFS的精髓啊 ps:也可用队列
{
//
rt = q[i].r;
xt = q[i].x+ext[rt].x; //只有直走的时候 x,y的坐标才会改变 并且和rt(即方向联系起来)
yt = q[i].y+ext[rt].y;
if(xt>=0&&xt<m&&yt>=0&&yt<n&&map[xt][yt]!='#'&&!visited[xt][yt][rt])
{
q[top].x = xt;
q[top].y = yt;
q[top].r = rt;
q[top++].l = q[i].l+1;
visited[xt][yt][rt] = 1;
if(map[xt][yt]=='T') return q[top-1].l; //返回的是top-1的值哦 因为最后top都是++了的
}
//
rt = (q[i].r+1)%4;
xt = q[i].x; //向左向右转 x y坐标不变
yt = q[i].y;
if(xt>=0&&xt<m&&yt>=0&&yt<n&&map[xt][yt]!='#'&&!visited[xt][yt][rt])
{
q[top].x = xt;
q[top].y = yt;
q[top].r = rt;
q[top++].l = q[i].l+1;
visited[xt][yt][rt]=1;
}
//
rt = (q[i].r+3)%4;
xt = q[i].x;
yt = q[i].y;
if(xt>=0&&xt<m&&yt>=0&&yt<n&&map[xt][yt]!='#'&&!visited[xt][yt][rt])
{
q[top].x = xt;
q[top].y = yt;
q[top].r = rt;
q[top++].l = q[i].l+1;
visited[xt][yt][rt] = 1;
}
}
return -1;
}
int main()
{
int cas,i,j;
cin>>cas;
while(cas--)
{
cin>>m>>n;
for(i=0;i<m;i++)
{
cin>>map[i];
for(j=0;j<n;j++)
{
if(map[i][j]=='S')
{
x = i;
y = j;
}
}
}
cout<<bfs()<<endl;
}
return 0;
}
本题是属于很基础的BFS题目 --!