[알고리즘] 그림 - 백준 1926

se.jeon·2023년 2월 27일
0

알고리즘

목록 보기
10/21
post-thumbnail

문제

과정

지난번에 풀었던 2178을 개선하였다.
https://velog.io/@dev_sieun/%EC%95%8C%EA%B3%A0%EB%A6%AC%EC%A6%98-%EB%AF%B8%EB%A1%9C-%ED%83%90%EC%83%89-%EB%B0%B1%EC%A4%80-2178


기본적인 BFS 형태에 현재 그림의 개수를 세기 위한 Picture를 스캔하는 반복문 구간을 주었고, 넓이를 세고 비교하는 구간을 주었다.

결과

//
// Created by 전시은 on 2023/02/27.
//
// 문제 :: 그림
// 링크 :: https://www.acmicpc.net/problem/1926
// 입력 :: 첫째 줄에 도화지의 세로 크기 n(1 ≤ n ≤ 500)과 가로 크기 m(1 ≤ m ≤ 500)이 차례로 주어진다. 두 번째 줄부터 n+1 줄 까지 그림의 정보가 주어진다. (단 그림의 정보는 0과 1이 공백을 두고 주어지며, 0은 색칠이 안된 부분, 1은 색칠이 된 부분을 의미한다)
// 출력 :: 첫째 줄에는 그림의 개수, 둘째 줄에는 그 중 가장 넓은 그림의 넓이를 출력하여라. 단, 그림이 하나도 없는 경우에는 가장 넓은 그림의 넓이는 0이다.

#include <iostream>
#include <queue>
using namespace std;

int nPicture1926[501][501];
int nVisit1926[501][501];


int main()
{
    cin.tie(NULL);
    ios_base::sync_with_stdio(false);

    int n, m;
    int nPicCount = 0;
    int nPicBiggest = 0;
    int nX[4] = { 0, 0, -1, 1};
    int nY[4] = { -1, 1, 0, 0};
    cin >> n >> m;

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

    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < m; j++)
        {
            if(nPicture1926[i][j] == 1 && nVisit1926[i][j] == 0)
            {
                int nCurrentPic = 0;
                queue<pair<int, int>> qBFS;
                qBFS.push(make_pair(i, j));
                nPicCount++;

                // bfs
                while(!qBFS.empty())
                {
                    pair<int, int> current = qBFS.front();
                    nVisit1926[current.first][current.second] = 1;
                    qBFS.pop();
                    nCurrentPic++;

                    for(int dir = 0; dir < 4; dir ++)
                    {
                        int dX = current.first + nX[dir];
                        int dY = current.second + nY[dir];

                        if (dX < 0 || dX >= n || dY < 0 || dY >= m) continue;
                        if (nVisit1926[dX][dY] == 1 || nPicture1926[dX][dY] == 0) continue;

                        nVisit1926[dX][dY] = 1;
                        qBFS.push(make_pair(dX, dY));
                    }
                }

                nPicBiggest = max(nPicBiggest, nCurrentPic);
            }
        }
    }

    cout << nPicCount << "\n" << nPicBiggest;

    return 0;
}
profile
취미 다이소

0개의 댓글