POJ 1915 简单 广搜题

题意要求是给出两个坐标,给出一个棋盘的大小,问用最小的步数 从初始坐标走到最后终点,

此题是典型的广搜题,但自己大意了,忘记把 标记数组visisted【】【】初始化了,以致于错了很多次,

 

就当给自己长教训吧

 

 

#include<iostream>
#include<queue>
#include<fstream>
using namespace std;
int bmp[8][2] = {{-2,-1},{-2,1},{-1,-2},{-1,2},{1,-2},{1,2},{2,-1},{2,1}};
int visited[310][310];
int N,T,p;
struct node{
int x;
int y;
int temp;
};
queue <node> vi;
node first,next,last,top,jian;
bool cheak(int a, int b)
{
if(a >= 0 && a < T && b >= 0 && b < T )
return true;
return false;
}
void bfs(int x,int y)
{
while(!vi.empty())
vi.pop();
//p = 0;
top.x = x;
top.y = y;
top.temp = 0;
vi.push(top);
visited[top.x][top.y] = 1;
while(!vi.empty())
{

jian = vi.front();
vi.pop();
for(int i = 0;i < 8; i++)
{
next.x = jian.x + bmp[i][0];
next.y = jian.y + bmp[i][1];
next.temp = jian.temp;
if(cheak(next.x ,next.y) && !visited[next.x][next.y] )
{
if(next.x == last.x && next.y == last.y)
{
p = next.temp+1;
return;
}
next.temp++;
visited[next.x][next.y] = 1;
vi.push(next);

}
}
}
}

int main()
{
ifstream cin("in.txt");
cin>>N;
while(N--)
{
memset(visited,0,sizeof(visited));
cin>>T;
cin>>first.x>>first.y>>last.x>>last.y;
first.temp = 0;
if(first.x == last.x && first.y == last.y)
p = 0;
else
bfs(first.x,first.y);

cout<<p<<endl;
}
}

posted on 2012-10-30 14:53  元点之始  阅读(232)  评论(0编辑  收藏  举报

导航