Topic Link: Fire Game
Test instructions: In a n*m rectangle, ' # ' stands for grass, '. ' On behalf of the open space, the empty place does not fire. Two people started firing at the same time, asking the shortest amount of time to spot all the grass and not output '-1 '.
Parse: First use DFS pre-judge the number of connected blocks of the grassland, more than 2 can not ignite all
Choose two grass as a starting point, both as a whole, the shortest time to search the starting point to all the meadows with BFS, and then retain the longest time
In all the longest time, choose the shortest, that is, the request.
AC Code:
#include <cstdio> #include <cstring> #include <queue> #include <utility>using namespace std; Char mz[11][11];int vis[11][11];int N, m, ans, res;queue<pair<int, int> > Q;bool vs[11][11][11][11];const int Dir[4][2] = {0, 1, 0,-1, 1, 0,-1, 0};void BFS (int x1, int y1, int x2, int y2) {memset (Vis, 0, sizeof (VIS)); while (!q.empty ()) Q.pop (); Q.push (Make_pair (x1, y1)); Q.push (Make_pair (x2, y2)); VIS[X1][Y1] = 1; Vis[x2][y2] = 1; res = 1; while (!q.empty ()) {pair<int, int> now = Q.front (); Q.pop (); int x = Now.first; int y = Now.second; for (int i=0; i<4; i++) {int tx = x + dir[i][0]; int ty = y + dir[i][1]; if (TX >=0 && TX < n && ty >= 0 && ty < m && mz[tx][ty] = = ' # ' &&!vis[ Tx][ty]) {Vis[tx][ty] = Vis[x][y] + 1; Q.push (Make_pair (TX, Ty)); if (res < vis[tx][ty]) res = VIS[tx][ty]; Record maximum Time}}}}void dfs (int x, int y) {//Search connected block vis[x][y] = 1; for (int i=0; i<4; i++) {int tx = x + dir[i][0]; int ty = y + dir[i][1]; if (TX >= 0 && TX < n && ty >= 0 && ty < m && mz[tx][ty] = = ' # ' &&!vis [TX] [Ty]) DFS (TX, Ty); }}bool OK () {///determine if the for (int i=0; i<n; i++) is fully lit for (int j=0; j<m; J + +) if (mz[i][j] = = ' # ' &am p;&!vis[i][j]) return false; return true;} int main () {#ifdef sxk freopen ("In.txt", "R", stdin); #endif//sxk int t; scanf ("%d", &t); for (int kase=1; kase<=t; kase++) {scanf ("%d%d", &n, &m); for (int i=0; i<n; i++) scanf ("%s", Mz[i]); memset (Vis, 0, sizeof (VIS)); Memset (VS, False, sizeof (VS)); int cnt = 0; for (int i=0, i<n; i++) for (int j=0; j<m; J + +) {if (!vis[i][j] && MZ[I][J] = = ' # ') {DFS (i, j); CNT + +; Record number of connected blocks}} ans = 0x7fffffff; printf ("Case%d:", Kase); if (CNT > 2) {puts ("-1"); continue;} Pretreatment, more than 2 blocks, it is impossible to all point while (!q.empty ()) Q.pop (); for (int i=0, i<n; i++) for (int j=0; j<m; J + +) {if (mz[i][j]! = ' # ') continue; for (int p=0, p<n; p++) for (int q=0; q<m; q++) {if (mz[p][q] = = ' # ' &&!v S[i][j][p][q]) {vs[i][j][p][q] = vs[p][q][i][j] = true; BFS (i, J, p, Q); if (ok () && res-1 < ans) ans = res-1; Find the smallest}} in printf ("%d\n", ans) for the longest time; } return 0;}
Copyright NOTICE: This article is sxk original article, reprint please attach this article link ^_^
Fzoj 2150 Fire Game (DFS + BFS)