성우리뷰

BFS 활용 중첩(14502)

두원공대88학번뚜뚜 2021. 10. 15. 21:51
#include <string>
#include <iostream>
#include <vector>
#include <queue>

#define MAX 8
using namespace std;

int arr[8][8];
int arrcopy[8][8];
int dx[4] = { 0,0,-1,1 };
int dy[4] = { 1,-1,0,0 };

int n, m;

vector<pair<int, int>> v;
int ret = 0;
void BFS() {
    queue<pair<int, int>> q;
    for (int i = 0; i < v.size(); i++) q.push(make_pair(v[i].first, v[i].second));

    while (!q.empty()) {
        int nx = q.front().first;
        int ny = q.front().second;
        q.pop();

        for (int i = 0; i < 4; i++) {
            int x = nx + dx[i];
            int y = ny + dy[i];

            if (x < 0 || x >= n || y < 0 || y >= m) continue;
            if (arrcopy[x][y] == 0) {
                arrcopy[x][y] = 2;
                q.push(make_pair(x, y));
            }
        }
    }
    
    int num = 0;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (arrcopy[i][j] == 0) num++;
   //         cout << arrcopy[i][j];
        }
    //    cout << "\n";
    }
   // cout << "\n";
    ret = ret < num ? num : ret;
    return;
}

void wall(int cnt, int row, int col) {
    if (cnt == 3) {
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                arrcopy[i][j] = arr[i][j];

        BFS();
        return;
    }

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (arr[i][j] == 0) {
                arr[i][j] = 1;
                wall(cnt + 1, i, j);
                arr[i][j] = 0;
            }
        }
    }
}

int main() {
    cin >> n >> m;

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cin >> arr[i][j];
            if (arr[i][j] == 2)
                v.push_back(make_pair(i, j));
        }
    }

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (arr[i][j] == 0) {
                arr[i][j] = 1;
                wall(1, i, j);
                arr[i][j] = 0;
            }
        }
    }

    cout << ret;
    return 0;
}