Portal: click me
The meaning of the question: "#" is grass, "." is a wall, ask if you can light two places, that is, light two "#", burn all the grass, if you can, then output the minimum required time, if not, output - 1
Idea: Violent BFS, see that n and m are not large, save each "#" directly, add 2 points each time to see if it can be burned, and then update ans.
#include <cstdio> #include <cstring> #include <cmath> #include <cstdlib> #include <ctime> #include <iostream> #include <algorithm> #include <sstream> #include <string> #include <vector> #include <queue> #include <stack> #include <map> #include <set> #include <utility> #include <bitset> using namespace std; #define LL long long #define pb push_back #define mk make_pair #define pill pair<int, int> #define mst(a, b) memset(a, b, sizeof a) #define REP(i, x, n) for(int i = x; i <= n; ++i) void closeio(){ cin.tie( 0 ); ios::sync_with_stdio(0); } struct note{ int x,y,step; }p,pos; char ma[ 20 ][ 20 ]; int vis[ 20 ][ 20 ]; int n,m; int go[ 4 ][ 2 ] = {{ 1 , 0 },{- 1 , 0 },{ 0 ,- 1 },{ 0 , 1 }};//Four directions void init(){ memset(vis,0,sizeof(vis)); } bool check(int x,int y){ if(x < 0 || x >= n || y < 0 || y >= m || vis[x][y] == 1){ return false; } return true; }//Determine whether it is out of bounds and has been visited bool judge(){ for(int i = 0 ; i < n ; i ++){ for(int j = 0 ; j < m ; j ++){ if(ma[i][j] == '#' && !vis[i][j]){ return false; } } } return true; } // Determine whether all are on fire int bfs( int x, int y, int a, int b){ int sum = 0 ; queue<note>q; q.push((note){x,y,0}); vis[x][y] = 1 ; q.push((note){a,b,0}); vis[a][b] = 1 ; // Add both points to the queue while (! q.empty()){ pos = q.front(); sum = pos.step; // The step of the last point in the queue is the required number of steps q.pop(); for ( int i = 0 ; i < 4 ;i ++ ){ int dx = pos.x + go [i][ 0 ]; int dy = pos.y + go[i][ 1 ]; if (check(dx,dy) && ma[dx][dy] == ' # ' ){ p.x = dx; py = dy; p.step = pos.step + 1; q.push(p); vis [dx] [dy] = 1 ; } } } return sum; } intmain () { int t,cas = 1; for(scanf("%d",&t);t--;){ vector<note>v; scanf("%d %d",&n,&m); for(int i = 0 ; i < n ; i++){ scanf("%s",ma[i]); for(int j = 0 ; j < m ; j ++){ if(ma[i][j] == '#'){ p.x = i;p.y = j;p.step = 0; v.push_back(p); } } } int ans = 10000000; for(int i = 0 ; i < v.size() ; i++){ for(int j = i ; j < v.size() ; j ++){ init(); int a = bfs(v[i].x,v[i].y,v[j].x,v[j].y); if(judge()){ years = min(y,years); } // If all are on fire, then the ans value is ans and the small one in this wide search } } printf( " Case %d: %d\n " ,case++,years == 10000000 ?- 1 :years); } return 0; }