40求调
查看原帖
40求调
1123415
songlinze楼主2025/7/26 22:34
#include<bits/stdc++.h>
using namespace std;
int n,m;
int xs,ys,xe,ye;
char a[510][510]; 
int vis[510][510]; 
int dx[4]={-1,1,0,0};
int dy[4]={0,0,-1,1};
struct point
{
	int x_i,y_i,step;
};
bool check(int x,int y)
{
	if(x<1 || y<1 || x>n || y>m) return 0;
	return 1;
}
void bfs()
{
	deque<point> q;
	point beg; 
	beg.x_i=xs,beg.y_i=ys; beg.step=0; 
	q.push_back(beg); vis[xs][ys]=1;
	while(!q.empty())
	{
		point noww=q.front(); q.pop_front();
		if(noww.x_i==xe && noww.y_i==ye)
		{
			printf("%d\n",noww.step);
			return ;
		}
		for(int i=0;i<4;i++)
		{
			point neww; neww.x_i=noww.x_i+dx[i]; neww.y_i=noww.y_i+dy[i];
			if(check(neww.x_i,neww.y_i) && !v[neww.x_i][neww.y_i]) 
			{
				vis[neww.x_i][neww.y_i]=1;
				if(a[neww.x_i][neww.y_i]==a[noww.x_i][noww.y_i])
				{
					neww.step=noww.step;
					q.push_front(neww);
				}
				else 
				{
					neww.step=noww.step+1;
					q.push_front(neww);
				}
			}
		}
	}
	return ;
}
int main()
{
	while(1)
	{
		memset(vis,0,sizeof(vis));
		scanf("%d %d",&n,&m); 
		if(n==0 && m==0) break;
		for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) cin>>a[i][j];
		scanf("%d %d %d %d",&xs,&ys,&xe,&ye);
		xs++,ys++,xe++,ye++;
		bfs();
	}
	return 0;
}
2025/7/26 22:34
加载中...