hdu 2354(bfs求最短路)

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

思路:初始化step[][]==inf,然后如果当前点p.step<step[p.x][p.y],则入优先队列。

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 #include<queue>
 6 using namespace std;
 7 #define inf 1<<30
 8 struct Node{
 9    int x,y,step;
10    bool operator < (const Node &p) const {
11       return p.step<step;
12    }
13 };
14 int n,m;
15 int Step[22][22];
16 char map[22][22];
17 int dir[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
18 
19 int bfs(){
20    for(int i=1;i<=n;i++)
21       for(int j=1;j<=m;j++)
22          Step[i][j]=inf;
23    priority_queue<Node>Q;
24    Node p,q;
25    for(int i=1;i<=m;i++){
26       p.x=1,p.y=i,p.step=1;
27       Q.push(p);
28    }
29    while(!Q.empty()){
30       p=Q.top();
31       Q.pop();
32       if(p.x==n)return p.step;
33       for(int i=0;i<4;i++){
34          q.x=p.x+dir[i][0];
35          q.y=p.y+dir[i][1];
36          q.step=p.step;
37          if(q.x<1||q.x>n||q.y<1||q.y>m)continue;
38          if(map[q.x][q.y]!=map[p.x][p.y])q.step++;
39          if(Step[q.x][q.y]>q.step){
40             Step[q.x][q.y]=q.step;
41             Q.push(q);
42          }
43       }
44    }
45    return 1;
46 }
47 
48 int main(){
49  //  freopen("1.txt","r",stdin);
50    int _case;
51    scanf("%d",&_case);
52    while(_case--){
53       scanf("%d%d",&n,&m);
54       for(int i=1;i<=n;i++)
55          scanf("%s",map[i]+1);
56       int ans=bfs();
57       printf("%d\n",ans);
58    }
59    return 0;
60 }
View Code

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值