2612两人路径和最短

    #include<cstdio>
    #include<iostream>
	#include<cstdlib>
	#include<cstring>
	#include<queue>
	using namespace std;
	struct node
	{
		int x, y, step;
	};//记录点的坐标以及到该点的时间
	int n, m;
	char map[209][209];
	int dx[4] = { 0,-1,0,1 };
	int dy[4] = { -1,0,1,0 };
	int vis[209][209], num[209][209];//vis标记数组,num记录到@的总时间
	bool judge(int x, int y)
	{
		if (x >= 0 && x < n&&y >= 0 && y < m )
			return true;
		return false;
	}
	void bfs(int x, int y)
	{
		queue<node> p;
		while (!p.empty())
			p.pop();
		node st;
		st.x = x;
		st.y = y;
		st.step = 0;
		p.push(st);
		vis[x][y] = 1;
		while (!p.empty())
		{
			node t = p.front();
			node next;
			p.pop();
			for (int i = 0; i < 4; i++)
			{
				next.x = t.x + dx[i];
				next.y = t.y + dy[i];
				next.step = t.step+1;
				if (judge(next.x, next.y)&&map[next.x][next.y]!='#' && !vis[next.x][next.y])
				{
					p.push(next);
					vis[next.x][next.y] = 1;
					if (map[next.x][next.y] == '@')//找到了一个出口就记录求和,别的路径不需要
						num[next.x][next.y] += next.step;
				}
			}

		}
	}
	int main()
	{
		int yx, yy, mx, my, i, j;
		while (~scanf("%d%d", &n, &m))
		{
			for (i = 0; i < n; ++i)
			{
				getchar();
				for (j = 0; j < m; ++j)
				{
					scanf("%c", &map[i][j]);
					if (map[i][j] == 'Y')
					{
						yx = i;
						yy = j;
					}
					else if (map[i][j] == 'M')
					{
						mx = i;
						my = j;
					}
				}
			}
			memset(vis, 0, sizeof(vis));//这题是两个人找,其实就是一个人,虽然BFS得到的是最短路,但是其实过程中如果有多个“出口”
			memset(num, 0, sizeof(num));//没一个的路径其实都被记录下来了,如果单人的话这种情况就需要剪枝,但多人的话就需要记录求和
			bfs(yx, yy);
			memset(vis, 0, sizeof(vis));
			bfs(mx, my);
			int ans = 9999999;
			for (i = 0; i < n; ++i)//找最小总时间
			{
				for (j = 0; j < m; ++j)
				{
					if (num[i][j] != 0 && ans > num[i][j])
						ans = num[i][j];
				}
			}
			printf("%d\n", ans * 11);
		}
		return 0;
	}

猜你喜欢

转载自blog.csdn.net/qq_40061421/article/details/79963109