數據結構_廣度優先搜索

★ 實驗任務
衆所周知,索隆是一個路癡,一天在一小島上,他又迷路了! !好基友山治心急如焚,
決定出去找他,由於練成了月步,山治的速度竟然達到了正無窮!小島上除了空地,還有盤
絲洞(簡稱 psd),盤絲洞裏住着可愛的妹紙,山治每次經過一個盤絲洞,都要停留一個單
位時間來欣賞妹紙, 給你一個 n*m 的地圖以及山治和索隆當前位置, 山治想請你幫他算算他
最快要多久才能見到索隆。
★ 數據輸入
輸入第一行爲兩個正整數 n,m (2 <=n,m <=1000),表示有 n 行 m 列,最左上角的座標爲
(1,1) 。
接下來 n 行,每行 m 個字符, “.”代表盤絲洞, “X”代表空地,只有‘.’和’X’兩種字
符,山治通過盤絲洞需 1 個單位時間,通過空地無需花費時間。
最後兩行分別表示山治和索隆的當前座標。 (你可以假設這兩個座標都在空地上,即
‘X’ ) 。
★ 數據輸出
對於每個詢問,輸出一行一個整數,表示山治最快見到索隆的時間。
輸入示例  輸出示例
6 6
..X...
XXX.X.
....X.
X.....
X.....
X.X...
3 5
6 3

3



1.廣度優先搜索

策略:

1.push當前點的未訪問過的上下左右點,

2.選取隊列中 dis最小的那個重複步驟1

3結束條件是:從隊列中選出的那個點就是終點時,返回dis

#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int N=1010;
bool G[N][N],vis[N][N];
int n,m;
struct node
{
    int x,y,dis;
    bool operator <(const node &a)const{
    return dis>a.dis;}
};
priority_queue<node> q;
void tovist(const node &cur,node &next)
{
    if(!vis[next.x][next.y]){
            vis[next.x][next.y]=true;
            next.dis=cur.dis+G[next.x][next.y];
            q.push(next);
    }
}
int bfs(const node&s,const node&e)
{
    node cur=s,next;
    cur.dis=0;
    int i,tmp1[]={1,-1,0,0};
    vis[s.x][s.y]=true;
    q.push(cur);
    while(!q.empty()){
        cur=q.top();q.pop();
        if(cur.x==e.x&&cur.y==e.y)return cur.dis;
        for(i=0;i<4;++i){
            next.x=cur.x+tmp1[i],next.y=cur.y+tmp1[3-i];
            if(next.x<0||next.x>=n||next.y<0||next.y>=m)continue;
            tovist(cur,next);
        }
    }
    return -1;
}
int main()
{
    int i,j,ans;
    char str[N];
    node s,e;
    while(~scanf("%d %d",&n,&m)){
        memset(vis,0,sizeof(vis));
        memset(G,0,sizeof(G));
        while(!q.empty())q.pop();
        for(i=0;i<n;++i){
            scanf("%s",str);
            for(j=0;j<m;++j)if(str[j]=='.')G[i][j]=true;
        }
        scanf("%d %d",&s.x,&s.y);
        --s.x,--s.y;
        scanf("%d %d",&e.x,&e.y);
        --e.x,--e.y;
        ans=bfs(s,e);
        printf("%d\n",ans);
    }

}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章