01BFS求改代码
  • 板块学术版
  • 楼主VectorChange
  • 当前回复6
  • 已保存回复6
  • 发布时间2021/9/20 20:16
  • 上次更新2023/11/4 06:02:13
查看原帖
01BFS求改代码
470194
VectorChange楼主2021/9/20 20:16

原题

#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
struct node {
	int x, y, t;
	bool operator<(const node& a) const {
		return t > a.t;
	}
};
int n, m;
int dx[4] = { 0,0,-1,1 }, dy[4] = { 1,-1,0,0 };
char map[1005][1005];
bool vis[1005][1005];
int dis[1005][1005];

inline int bfs() {
	priority_queue<node> q;
	q.push(node{1,1,0});
	vis[1][1] = true;
	memset(dis,0x3f3f3f3f,sizeof(dis));
	dis[1][1]=0;
	while(!q.empty()) {
		int nx = q.top().x, ny = q.top().y, nt = q.top().t;
		q.pop();
		for (int i = 0; i < 4; i++) {
			int tx = nx + dx[i], ty = ny + dy[i];
			if (tx >= 1 && tx <= n && ty >= 1 && ty <= m ) {
				if (map[tx][ty] != map[nx][ny] && dis[tx][ty]>dis[nx][ny]+1) 
					dis[tx][ty]=dis[nx][ny]+1;
				else 
					if(map[tx][ty] == map[nx][ny] && dis[tx][ty]>dis[nx][ny]) 
						dis[tx][ty]=dis[nx][ny];
				if(!vis[tx][ty]) {
					q.push(node{tx,ty,dis[tx][ty]});
					vis[tx][ty] = true;
				}
			}
		}
	}
	return dis[n][m];
}
int main() {
	int T;
	scanf("%d",&T);
	while (T--) {
		scanf("%d%d",&n,&m);
		for (int i=1;i<=n;i++)
			for (int j=1;j<=m;j++)
				cin>>map[i][j];
		memset(vis,false,sizeof(vis));
		cout<<bfs()<<endl;
	}
	return 0;
}

实在找不出错误了,就是WA...

2021/9/20 20:16
加载中...