1. 程式人生 > >bearBaby loves sleeping

bearBaby loves sleeping

https://ac.nowcoder.com/acm/contest/338/B

題解:BFS裸題

/*
*@Author:   STZG
*@Language: C++
*/
#include <bits/stdc++.h>
#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<string>
#include<vector>
#include<bitset>
#include<queue>
#include<deque>
#include<stack>
#include<cmath>
#include<list>
#include<map>
#include<set>
//#define DEBUG
#define RI register int
using namespace std;
typedef long long ll;
//typedef __int128 lll;
const int N=10000+10;
const int MOD=1e9+7;
const double PI = acos(-1.0);
const double EXP = 1E-8;
const int INF = 0x3f3f3f3f;
int t,n,m,k,q,ans;
int a[N][N];
char str;
int x,y;
int vis[110][110];
int b[][2]={1,0,0,1,-1,0,0,-1};
struct node
{
     int x;
     int y;
     int lev;
}front1,tmp,start,end1;
    queue <node>Q;
int  bfs(node s,node e){

    while(!Q.empty())
        Q.pop();
	Q.push(s);
    while(!Q.empty()){
        front1=Q.front();
        Q.pop();
        //cout<<front1.x<<" "<<front1.y<<" "<<front1.lev<<endl;
        for(int i=0;i<4;i++){
            tmp.x=b[i][0]+front1.x;
            tmp.y=b[i][1]+front1.y;
			tmp.lev=front1.lev;
            tmp.lev++;
            if(e.x==tmp.x&&e.y==tmp.y){
            	return tmp.lev;
			}
            if(tmp.x>=1&&tmp.x<=n&&tmp.y>=1&&tmp.y<=m&&a[tmp.x][tmp.y]!=1&&vis[tmp.x][tmp.y]==0){
 					vis[tmp.x][tmp.y]=1;//cout<<tmp.x<<" "<<tmp.y<<" "<<tmp.lev<<endl;
                	Q.push(tmp);
          	}
        }
    }
    return -1;
}

int main()
{
#ifdef DEBUG
	freopen("input.in", "r", stdin);
	//freopen("output.out", "w", stdout);
#endif
        scanf("%d%d",&n,&m);
        scanf("%d%d",&x,&y);
        for(int i=1;i<=n;i++)
            for(int j=1;j<=m;j++)
                scanf("%d",&a[i][j]);
        vis[1][1]=1;
        start.x=1;
        start.y=1;
        start.lev=0;

        end1.x=x;
        end1.y=y;

        cout<<bfs(start,end1)<<endl;
    //cout << "Hello world!" << endl;
    return 0;
}