有優先級的BFS

http://acm.hdu.edu.cn/showproblem.php?pid=3023

#include<string.h>
#include<stdio.h>
#include<queue>
using namespace std;
int n, m;
int sx, sy, ex, ey;
char graph [1005][1005];
int dis[1005][1005];
int chang[1005][1005];
bool vis[1005][1005];
struct point{
    int x, y, change, step;
    bool operator < (const point& b)const{
        if (change == b.change){ return step > b.step; }
        return change > b.change;
    }
};
int to[8][2]={{-1,0},{1,0},{0,-1},{0,1},{-1,-1},{-1,1},{1,-1},{1,1}};
void BFS(){
        priority_queue<point> que;
        memset(dis, 0x3f, sizeof(dis));
        dis[sx][sy] = 1;
        memset(chang, 0x3f, sizeof(chang));
        chang[sx][sy] = 0;
        memset(vis, 0, sizeof(vis));
        que.push({ sx, sy, 0, 1 });
        while (!que.empty())
        {
            point curr = que.top();
            que.pop();
            vis[curr.x][curr.y] = 1;
            if (curr.x == ex&&curr.y == ey)break;
            for (int i = 0; i < 8; i++){
                point next = { curr.x + to[i][0], curr.y + to[i][1], curr.change, curr.step + 1 };
                if (next.x >= 0 && next.x < n&&next.y >= 0 && next.y < m&&graph[next.x][next.y]!='0'&&vis[next.x][next.y] == 0){
                    if (graph[next.x][next.y] != graph[curr.x][curr.y]){
                        next.change++;
                }
                if (next.change < chang[next.x][next.y]||(next.change==chang[next.x][next.y]&&next.step<dis[next.x][next.y])){
                        chang[next.x][next.y] = next.change;
                        dis[next.x][next.y] = next.step;
                        que.push(next);
                }
            }
        }
    }
   // while (!que.empty())que.pop();
}

int main(){
    while (~scanf("%d%d", &n, &m)){
        scanf("%d%d%d%d", &sx, &sy, &ex, &ey);
        sx--, sy--, ex--, ey--;
        for(int i=0;i<n;i++)
        {
            getchar();
            for(int j=0;j<m;j++)
            {
                //scanf("%c",&G[i][j]);
                //cin>>G[i][j];
                graph[i][j]=getchar();
            }
                //getchar();
        }
        BFS();
        if (chang[ex][ey] == 0x3f3f3f3f){ printf("0 0\n"); }
        else{ printf("%d %d\n", dis[ex][ey], chang[ex][ey]); }
    }
    return 0;
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 相信每一位玩ACM程序設計競賽的同學來說,都有一個從入門到精通的過程,而且分享他們經驗的時候,見到最多的就是一種合...
    FinlayLiu閱讀 5,440評論 6 182
  • 我愛家鄉的葡萄 我的家鄉在新疆、那里一個瓜果飄香的地方。我們那里出產許多水果,有香梨、葡萄、哈密瓜、西瓜等等…… ...
    xiaoxiaoningxia閱讀 580評論 1 2
  • 與之相念/文 吃面是一件很尋常的事兒。從小到大,我們都吃過無數次的面...
    與之相念閱讀 667評論 0 5
  • 有時候回憶起過往,猶如電影一般,突然覺得不真實。我們經歷著自己的故事,也在旁觀著別人的生活。 今天的天氣一整天都...
    執燈尋影閱讀 303評論 0 0
  • 文|禾甜 圖|網絡 1、 那晚,崔健出現在洪山體育館。 全場燈光熄滅。 熒熒的打火機光芒中,他將一塊紅布覆上了雙眼...
    禾田飛歌閱讀 458評論 0 5