百练+BFS+模版化解题

点击打开链接
//
//  main.cpp
//  test
//
//  Created by 吴有堃 on 2017/9/11.
//  Copyright © 2017年 吴有堃. All rights reserved.
//

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <cstring>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <queue>
const int maxn=25;
using namespace std;
struct Node{
    int x,y,steps;
};
queue<Node>Q;
char Arr[maxn][maxn],vis[maxn][maxn];
int Move[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
int M=0,N=0,xx=0,yy=0;

void find_loc()
{
    int i=0,j=0;
    for(i=0;i<M;i++){
        for(j=0;j<N;j++){
            if(Arr[i][j]=='@'){
                xx=i; yy=j;
                return ;
            }
        }
    }
}
void BFS()
{
    while (!Q.empty()) Q.pop();
    memset(vis,0,sizeof(vis));
    Node temp1,temp2;
    temp1.x=xx; temp1.y=yy;temp1.steps=0;
    vis[xx][yy] = 1;
    Q.push(temp1);
    while (!Q.empty()) {
        temp1=Q.front(); Q.pop();
        if(Arr[temp1.x][temp1.y]=='*'){
            printf("%d\n",temp1.steps);
            return;
        }
        for(int i=0;i<4;i++){
            temp2 =temp1;
            temp2.x+=Move[i][0]; temp2.y+=Move[i][1];
            if(temp2.x>=0&&temp2.x<M&&temp2.y>=0&&temp2.y<N&&!vis[temp2.x][temp2.y]
               &&Arr[temp2.x][temp2.y]!='#'){
                temp2.steps +=1;
                vis[temp2.x][temp2.y] =1;
                Q.push(temp2);
            }
        }
    }
    printf("-1\n");
}
int main(int argc, const char * argv[]) {
    // insert code here...
    int i=0;
    while (scanf("%d %d",&M,&N)) {
        if(M==0&&N==0) break;
        for(i=0;i<M;i++) scanf("%s",Arr[i]);
        find_loc();
        BFS();
    }
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值