출처: https://bumcrush.tistory.com/182 [맑음때때로 여름]

상세 컨텐츠

본문 제목

백준 1926 그림(dfs)

알고리즘

by 장동균 2021. 1. 14. 22:39

본문

www.acmicpc.net/problem/1926

 

1926번: 그림

어떤 큰 도화지에 그림이 그려져 있을 때, 그 그림의 개수와, 그 그림 중 넓이가 가장 넓은 것의 넓이를 출력하여라. 단, 그림이라는 것은 1로 연결된 것을 한 그림이라고 정의하자. 가로나 세로

www.acmicpc.net

#include <iostream>

using namespace std;
const int MAX = 500;

typedef struct
{
    int x, y;
} Dir;

Dir dirMove[4] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
bool visited[MAX][MAX];
int graph[MAX][MAX];
int n, m;
int cnt;
int area;
int maxArea;
void dfs(int x, int y)
{
    visited[x][y] = true;
    area++;
    if (area > maxArea)
        maxArea = area;
    for (int i = 0; i < 4; i++)
    {
        int nextX = x + dirMove[i].x;
        int nextY = y + dirMove[i].y;
        if (!visited[nextX][nextY] && graph[nextX][nextY])
        {
            if (0 <= nextX && nextX < n && 0 <= nextY && nextY < m)
            {
                dfs(nextX, nextY);
            }
        }
    }
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    cin >> n >> m;
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            cin >> graph[i][j];
        }
    }
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            if (graph[i][j] && !visited[i][j])
            {
                dfs(i, j);
                area = 0;
                cnt++;
            }
        }
    }
    cout << cnt << "\n";
    cout << maxArea;
}

그냥 일반적인 dfs 모양의 문제.

관련글 더보기

댓글 영역