Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <queue>
- #include <vector>
- #include <cstring>
- using namespace std;
- const int di[4] = {-1, 1, 0, 0};
- const int dj[4] = {0, 0, -1, 1};
- int bfs(int n, int m, vector<string> & v) {
- bool visited[n][m];
- int res = 0;
- memset(visited, false, sizeof visited);
- for(int i = 0; i < n; i++) {
- for(int j = 0; j < m; j++) {
- if(!visited[i][j] and v[i][j] == '.') {
- queue<int> q;
- q.push(i);
- q.push(j);
- res++;
- while(!q.empty()) {
- int ci = q.front(); q.pop();
- int cj = q.front(); q.pop();
- for(int k = 0; k < 4; k++) {
- int ti = ci + di[k];
- int tj = cj + dj[k];
- if(ti >= 0 and ti < n and tj >= 0 and tj < m and !visited[ti][tj] and v[ti][tj] == '.') {
- q.push(ti);
- q.push(tj);
- visited[ti][tj] = true;
- }
- }
- }
- }
- }
- }
- return res;
- }
- int main(){
- ios_base::sync_with_stdio(false);
- int n, m;
- cin >> n >> m;
- char mat[n][m];
- for(int i = 0; i < n; i++) {
- for(int j = 0; j < m; j++) {
- cin >> mat[i][j];
- }
- }
- int res = 2e9;
- for(int R = 0; R < n; R++) {
- vector<string> v;
- for(int i = 0; i < n; i++) {
- if(i != R) {
- string tmp = "";
- for(int j = 0; j < m; j++) {
- tmp += mat[i][j];
- }
- v.push_back(tmp);
- }
- }
- res = min(res, bfs(n - 1, m, v));
- }
- for(int C = 0; C < m; C++) {
- vector<string> v;
- for(int i = 0; i < n; i++) {
- string tmp = "";
- for(int j = 0; j < m; j++) {
- if(j != C) {
- tmp += mat[i][j];
- }
- }
- v.push_back(tmp);
- }
- res = min(res, bfs(n, m - 1, v));
- }
- cout << res << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment