01BFS

sad_lin發表於2024-09-17

P4554 小明的遊戲

大部分 bfs 題都可以用最短路做,而最短路中 dijkstra 用堆最佳化保證權值小的優先操作,而這題權值只有 01 兩種,所以用 01bfs,具體用 deque 操作,增加權值為 0 時(同色),放到隊頭,增加的權值為 1 時(異色),放到隊尾,相當於直接 \(O(1)\) 排序好了。

#include <bits/stdc++.h>
using namespace std;
int n,m;
int sx,sy,tx,ty;
char c[505][505];
struct ss{
	int x,y,w;
};
deque<ss> q;
bool vis[505][505];
int xx[5]={1,-1,0,0};
int yy[5]={0,0,1,-1};
int dfs01(){
	while(!q.empty()){
		q.pop_front();
	}
	q.push_back({sx,sy,0});
	while(!q.empty()){
		ss u=q.front();
		q.pop_front();
		int x=u.x;
		int y=u.y;
		int w=u.w;
		vis[x][y]=1;
		if(x==tx&&y==ty){
			return w;
		}
		for(int i=0;i<4;i++){
			int xa=x+xx[i];
			int ya=y+yy[i];
			if(xa<0||xa>=n||ya<0||ya>=m){
				continue;
			}
			if(vis[xa][ya]==0){
				if(c[xa][ya]==c[x][y]){
					q.push_front({xa,ya,w+0});
				}
				else{
					q.push_back({xa,ya,w+1});
				}
			}
		}
	}
	return 0;
}

int main(){
    ios::sync_with_stdio(false);
	while(1){
		cin>>n>>m;
		if(n==0&&m==0){
			break;
		}
		for(int i=0;i<n;i++){
			for(int j=0;j<m;j++){
				cin>>c[i][j];
			}
		}
		cin>>sx>>sy>>tx>>ty;
		cout<<dfs01()<<"\n";
		for(int i=0;i<n;i++){
			for(int j=0;j<m;j++){
				vis[i][j]=0;
			}
		}
	}
    return 0;
}