알고리즘/백준

1926 그림

맛있는김치찜 2020. 10. 12. 01:15
#include <iostream>
#include <queue>

using namespace std;

typedef struct
{
    int row;
    int column;
} dot;

int dr[] = {0, 0, -1, 1};
int dc[] = {1, -1, 0, 0};
int n, m;
int graph[500][500] = {-1, };
bool check[500][500] = {false, };
int pictureNum;
int picture[250 * 500] = {0, };

int bfs(dot start)
{
    queue<dot> q;
    q.push(start);
    check[start.row][start.column] = true;
    int pictureSize = 1;

    while (!q.empty()) {
        dot next = q.front();
        q.pop();
        for (int i = 0; i < 4; i++) {
            int nextr = next.row + dr[i];
            int nextc = next.column + dc[i];
            if (!(graph[nextr][nextc] == 1 && nextr >= 0 && nextr < n && nextc >= 0 && nextc < m)) {
                continue;
            }
            if (check[nextr][nextc] == false) {
                q.push({nextr, nextc});
                check[nextr][nextc] = true;
                pictureSize++;
            }
        }
    }
    pictureNum++;
    
    return pictureSize;
}

void solve()
{
    int bigpictureSize = 0;

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (check[i][j] == false && graph[i][j] == 1) {
                picture[pictureNum] = bfs({i, j});
            }
        }
    }

    for (int i = 0; i < pictureNum; i++) {
        if (picture[i] > bigpictureSize) {
            bigpictureSize = picture[i];
        }
    }

    cout << pictureNum << endl;
    cout << bigpictureSize << endl;
}

void input()
{
    cin >> n >> m;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cin >> graph[i][j];
        }
    }
}

int main(void)
{
    input();
    solve();

    return 0;
}

문제의 알고리즘 분류를 보면 깊이우석탐색이라고 써있는데 그냥 bfs로 풀어도 상관 없었다.

주어진 배열을 훑어보면서 1이 나타나면 bfs를 통해 넓이를 구하고 저장했다.

어짜피 나올 수 있는 그림의 최대 갯수는 (가로 * 세로 / 2)개이니 그냥 최대 배열을 선언해서 넓이를 저장했다.

'알고리즘 > 백준' 카테고리의 다른 글

4811 알약  (0) 2020.10.12
5557 1학년  (0) 2020.10.12
2251 물통  (0) 2020.10.12
2234 성곽  (0) 2020.10.12
2023 신기한 소수  (0) 2020.10.12