[TJOI2008]Binary Land——[BFS]

[TJOI2008]Binary Land——[BFS]_第1张图片
[TJOI2008]Binary Land——[BFS]_第2张图片
【题意分析】

本来想做dp题的,然后发现这是道sb宽搜

直接来,暴力bfs,注意点是vis[][][][]数组要有四维(记录两个人的信息)

还有一只企鹅往左走,另一只企鹅往右走

输入字符用cin,还不能关流同步,不然会错,挺玄学的

getchar判断回车也会错

这个sb错误浪费了我好多时间

Code:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define MAXN 32
using namespace std;

struct Node {
	int gx, gy, mx, my, dist;
}o, u;

queue <Node> q;
char map[MAXN][MAXN];
bool vis[MAXN][MAXN][MAXN][MAXN];
int dx[MAXN], dy[MAXN], n, m, ans = -1;

void BFS () {
	vis[o.gx][o.gy][o.mx][o.my] = 1, q.push (o);
	while (! q.empty ()) {
		o = q.front (), q.pop ();
		for (register int i = 1; i <= 4; i++) {
			u.gx = o.gx + dx[i], u.gy = o.gy + dy[i];
			u.mx = o.mx + dx[i], u.my = o.my - dy[i];
			u.dist = o.dist + 1;
			if (map[u.gx][u.gy] == '#') u.gx = o.gx, u.gy = o.gy;
			if (map[u.mx][u.my] == '#') u.mx = o.mx, u.my = o.my;
			if (map[u.gx][u.gy] == 'T' && map[u.mx][u.my] == 'T') {
				ans = u.dist; return;
			}
			if (u.gx >= 1 && u.gx <= n && u.gy >= 1 && u.gy <= m
				&& u.mx >= 1 && u.mx <= n && u.my >= 1 && u.my <= m
				&& map[u.gx][u.gy] != 'X' && map[u.mx][u.my] != 'X'
				&& ! vis[u.gx][u.gy][u.mx][u.my])
					vis[u.gx][u.gy][u.mx][u.my] = 1, q.push (u);
		}
	}
}

int main () {
	dx[1] = -1, dx[2] = 0, dx[3] = 1, dx[4] = 0;
	dy[1] = 0, dy[2] = -1, dy[3] = 0, dy[4] = 1;
	scanf ("%d%d", &n, &m);
	for (register int i = 1; i <= n; i++)
		for (register int j = 1; j <= m; j++) {
			cin >> map[i][j];
			if (map[i][j] == 'G') o.gx = i, o.gy = j;
			if (map[i][j] == 'M') o.mx = i, o.my = j;
		}
	o.dist = 0, BFS ();
	if (ans == -1) puts ("no"); else printf ("%d\n", ans);
	return 0;
}

你可能感兴趣的:(搜索)