这几周一直在研究广度优先搜索node之类的问题,下午正好有机会和大家讨论一下.
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1242
题目粗心:在含有障碍的迷宫中求从一点到一点的最短时光或步数,这个题目有个坑爹的地方,天使的友人不止一个,所以搜索的起点应该是从天使开始搜到友人为止,最短路,还有一个坑爹的地方,题目求的是最短时光,不是最短步数,所以应该才用优先队列,小步数优先,结果我两种方法都试过,都能AC;
上代码:187MS 440K
每日一道理
水仙亭亭玉立,兰花典雅幽香,牡丹雍容华贵,梨花洁白无暇……美丽的花朵总能得到世人的羡慕与赞叹,殊不知,它从一粒小小的种子到最后开花,要历经无数的艰辛与坎坷!我们的成长也是如此。只有做辛勤的“织梦者”,我们的梦想才会成真!
水仙亭亭玉立,兰花典雅幽香,牡丹雍容华贵,梨花洁白无暇……美丽的花朵总能得到世人的羡慕与赞叹,殊不知,它从一粒小小的种子到最后开花,要历经无数的艰辛与坎坷!我们的成长也是如此。只有做辛勤的“织梦者”,我们的梦想才会成真!
#include <iostream>
#include <string>
#include <cstdio>
#include <cmath>
#include <vector>
#include <algorithm>
#include <sstream>
#include <cstdlib>
#include <fstream>
#include <queue>
using namespace std;
struct node{
int x,y,step;
};
/*
bool operator<(node a,node b){
return a.step > b.step;
}*/
queue<node> Q;
//priority_queue<node> Q;
bool visit[210][210];
char maze[210][210];
int dir[4][2]={{-1,0},{1,0},{0,1},{0,-1}};
int sum,m,n,sx,sy,endx,endy;
bool isbound(int a,int b){
if(a<1 || a>m || b<1 || b>n)return true;
return false;
}
void bfs(){
node p,q;
p.x=sx;
p.y=sy;
p.step=0;
Q.push(p);
while(!Q.empty())
{
p=Q.front();
Q.pop();
if(p.x==endx&&p.y==endy){cout<<p.step<<endl;return;}
for(int i=0;i<4;i++)
{
q.x=p.x+dir[i][0];
q.y=p.y+dir[i][1];
if(isbound(q.x,q.y))continue;//边界
if(maze[q.x][q.y]=='#')continue;//障碍
if(visit[q.x][q.y])continue; //判重
if(maze[q.x][q.y]=='.'||maze[q.x][q.y]=='r'){ //注意搜素方向
q.step=p.step+1;
visit[q.x][q.y]=1;
Q.push(q);
}
if(maze[q.x][q.y]=='x'){
q.step=p.step+2; //这是守卫的情况
visit[q.x][q.y]=1;
Q.push(q);
}
}
}
cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;
}
int main()
{
// ifstream fin;
// fin.open("data1.txt");
while(cin>>m>>n)
{
while(!Q.empty())Q.pop();
for(int i=1;i<=m;i++){
for(int j=1;j<=n;j++){
cin>>maze[i][j];
if(maze[i][j]=='r'){
endx=i;
endy=j;
}
if(maze[i][j]=='a'){
sx=i;
sy=j;
}
}
}
memset(visit,0,sizeof(visit));
visit[sx][sy]=1;
bfs();
}
return 0;
}
文章结束给大家分享下程序员的一些笑话语录: 腾讯的动作好快,2010年3月5日19时28分58秒,QQ同时在线人数1亿!刚刚看到编辑发布的文章,相差才2分钟,然后连专题页面都做出来了,他们早就预料到了吧?(其实,每人赠送10Q币,轻轻松松上两亿!)
--------------------------------- 原创文章 By
广度优先搜索和node
---------------------------------