书山有径勤为路>>>>>>>>

<<<<<<<<学海无涯苦作舟!

BFS寻求最短距离

题目:http://acm.swust.edu.cn/oj/problem/4/

这是一道简单的题目,但是可以说明问题了。

 

View Code
#include "iostream"
#include "string"
#include "cstdio"
#include "cstring"
#include "algorithm"
#include "queue"
using namespace std;
char Map[105][105];
int Used[105][105];
int Dir[4][2]={{0, 1}, {0, -1}, {-1, 0}, {1, 0}};
int T, N, M, i, j, k, si, sj;
struct Dot
{
int x, y;
int Step;
};

int BFS()
{
Used[si][sj] = 1;
Dot tmp;
queue<Dot> Q;
tmp.x = si;
tmp.y = sj;
tmp.Step = 0;
Q.push(tmp);
while(!Q.empty())
{
tmp = Q.front();
Q.pop();
for(i=0; i<4; i++)
{
Dot tmp2;
tmp2.x = tmp.x+Dir[i][0];
tmp2.y = tmp.y+Dir[i][1];
if(tmp2.x>=0 && tmp2.x<N && tmp2.y>=0 && tmp2.y<M && Used[tmp2.x][tmp2.y]==0)
{
if(Map[tmp2.x][tmp2.y]=='-')
{
tmp2.Step = tmp.Step+1;
Used[tmp2.x][tmp2.y]=1;
Q.push(tmp2);
}
else if(Map[tmp2.x][tmp2.y]=='E') return (tmp.Step+1);
}
}
}
return -1;
}

int main()
{
cin>>T;
while(T--)
{
cin>>N>>M;
memset(Used, 0, sizeof(Used));
for(i=0; i<N; i++)
for(j=0; j<M; j++)
{
cin>>Map[i][j];
if(Map[i][j]=='S')
{
si = i;
sj = j;
}
}
cout<<BFS()<<endl;
}
}



posted on 2011-12-01 12:14  More study needed.  阅读(277)  评论(0编辑  收藏  举报

导航

书山有径勤为路>>>>>>>>

<<<<<<<<学海无涯苦作舟!