Loading...

搜索小练#10

题目

thought:

1.make two queue, one is for J, another is for F

2.first update the J,and then uodate the F

the code is follow:

#include <bits/stdc++.h>
using namespace std;
//我一定要去寻找,就算无尽的星辰令我的探寻希望渺茫,就算我必须单枪匹马
const int N = 1e3+66;

int n, m, T;
int vis[N][N];
char ch[N][N];

int dx[5] = {0, 0, 1, -1};
int dy[5] = {1, -1, 0, 0};

struct node {int x, y;node(int x, int y):x(x), y(y){}};

inline void bfs () {
	queue<node>jq, fq;
	for (int i = 0; i < n; ++ i)
		for (int j = 0; j < m; ++ j) {
			if (ch[i][j] == 'J') {
				jq.push(node(i, j));
				vis[i][j] = 1;
			} else if (ch[i][j] == 'F') {
				fq.push(node(i, j));
				ch[i][j] = '#';
			}
		}
	
	int step(0);
	while (jq.size()) {
		++ step;
		for (int i = 0, j = jq.size(); i < j; ++ i) {
			node tmp = jq.front(); jq.pop();
			if (ch[tmp.x][tmp.y] == '#') continue;
			for (int k = 0; k < 4; ++ k) {
				int nx = tmp.x+dx[k], ny = tmp.y+dy[k];
				if (nx >= 0 && nx < n && ny >= 0 && ny < m) {
					if (ch[nx][ny] != '#' && !vis[nx][ny])
						vis[nx][ny] = 1, jq.push(node(nx, ny));
				}
				else {cout << step << '\n'; return;}
			}
		}
		for (int i = 0, j = fq.size(); i < j; ++ i) {
			node tmp = fq.front(); fq.pop();
			for (int k = 0; k < 4; ++ k) {
				int nx = tmp.x+dx[k], ny = tmp.y+dy[k];
				if (nx >= 0 && nx < n && ny >= 0 && ny < m && ch[nx][ny] != '#')
					ch[nx][ny] = '#', fq.push(node(nx, ny));
			}
		}
	}
	puts ("IMPOSSIBLE");
}

int main () {
	cin >> T;
	while (T --> 0) {
		cin >> n >> m;
		for (int i = 0; i < n; ++ i) scanf ("%s", ch[i]);
		bfs ();
		memset (vis, 0, sizeof vis);
	}
	return 0;
}
posted @ 2020-07-23 14:17  Youngore  阅读(80)  评论(0)    收藏  举报