题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3137

XXXXXXXXXXXXXX X XXX X XFXXXXX X XXX XX XX X X S X XX XXXXXX X X X X X X X X X X X XXX XX X XXXXXXXXXXXXXX
1 10 14 XXXXXXXXXXXXXX X XXX X XFXXXXX X XXX XX XX X X S X XX XXXXXX X X X X X X X X X X X XXX XX X XXXXXXXXXXXXXX
29
题意:
最少的步数从S走到F,每次只能走当前方向的右方或者直走!
X代表不能走!
代码如下:
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
const int maxn = 26;
int xx[4] = {-1,0,1,0};
int yy[4] = {0,1,0,-1};
int vis[5][maxn][maxn];
char mm[maxn][maxn];
int n, m;
int x1, y1;//起点
int x2, y2;//终点
struct node
{
int x;
int y;
int step;
int dir;//标记方向
};
int judge(int a, int b)
{
if(a>=0 && a<n && b>=0 && b<m)
return 1;
return 0;
}
int BFS()
{
memset(vis,-1,sizeof(vis));
node frontt, next;
queue<node>p,q;
int tx, ty;
for(int i = 0; i < 4; i++)
{
tx = x1 + xx[i];
ty = y1 + yy[i];
if(mm[tx][ty] != 'X')
{
frontt.x = tx;
frontt.y = ty;
frontt.step = 0;
frontt.dir = i;
q.push(frontt);
vis[i][tx][ty] = 1;
}
}
while(!q.empty())
{
frontt = q.front();
q.pop();
if(frontt.x == x2 && frontt.y == y2)
{
return frontt.step+1;
}
for(int i = 1; i <= 2; i++)
{
if(i == 1)
{
next.dir = frontt.dir;//当前方向继续向前
}
else
{
next.dir = (frontt.dir+1)%4;//向当前方向的右方
}
tx = frontt.x + xx[next.dir];
ty = frontt.y + yy[next.dir];
next.step = frontt.step+1;
if(mm[tx][ty]!='X' && judge(tx,ty) && (next.step<vis[next.dir][tx][ty] || vis[next.dir][tx][ty]==-1))
{
next.x = tx;
next.y = ty;
vis[next.dir][tx][ty] = next.step;
q.push(next);
}
}
}
}
int main()
{
#define ONLINE_JUDGE
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
getchar();
for(int i = 0; i < n; i++)
{
gets(mm[i]);
}
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
if(mm[i][j] == 'S')
{
x1 = i;
y1 = j;
}
else if(mm[i][j] == 'F')
{
x2 = i;
y2 = j;
}
}
}
int ans = BFS();
printf("%d\n",ans);
}
return 0;
}
原文地址:http://blog.csdn.net/u012860063/article/details/40833649