C++求助大佬,心态爆炸,WA一个
查看原帖
C++求助大佬,心态爆炸,WA一个
571939
A_pier楼主2021/11/17 21:27
#include<iostream>
#include<queue>
#include<algorithm>
#include<map>
using namespace std;
struct xy
{
	int x, y;
}top, node, fin;
int n, m;
char m0[400][400];
bool vis[400][400] = { false };
int path[400][400] = { 0 };
int dx[4] = { 1,-1,0,0 }, dy[4] = { 0,0,1,-1 };
queue<xy>q;

void goto_another(int &x, int &y)
{
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			if (i == x && j == y)
				continue;
			if (m0[i][j] == m0[x][y]) {
				path[i][j] = path[x][y];
				x = i;
				y = j;
				return;
			}
		}
	}
}

void bfs(int x, int y)
{
	q.push(node);
	vis[node.x][node.y] = true;
	path[node.x][node.y] = 0;
	while (!q.empty()) {
		top = q.front();
		q.pop();
		if (vis[fin.x][fin.y])
			return;
		if (m0[top.x][top.y] >= 'A'&&m0[top.x][top.y] <= 'Z')
			goto_another(top.x, top.y);
		for (int i = 0; i < 4; i++) {
			node.x = top.x + dx[i];
			node.y = top.y + dy[i];
			if (node.x < 0 || node.x >= n || node.y < 0 || node.y >= m || m0[node.x][node.y] == '#' || vis[node.x][node.y])
				continue;
			vis[node.x][node.y] = true;
			path[node.x][node.y] = path[top.x][top.y] + 1;
			q.push(node);
		}
	}
}

int main()
{
	cin >> n >> m;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			cin >> m0[i][j];
			if (m0[i][j] == '@') {
				node.x = i;
				node.y = j;
			}
			else if (m0[i][j] == '=') {
				fin.x = i;
				fin.y = j;
			}
		}
	}
	bfs(node.x, node.y);
	cout << path[fin.x][fin.y] << endl;

	return 0;
}
2021/11/17 21:27
加载中...