백준 알고리즘(C++)

백준 2234번 성곽 ( C++ )

coding232624 2024. 8. 29. 15:47

문제

https://www.acmicpc.net/problem/2234

 

해설

커넥티드 컴퍼넌트를 이용한 문제

옆의 집합과 합치는 과정을 신경써야함

 

코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <iostream>
#include <algorithm>
 
using namespace std;
 
int visited[54][54], mp[54][54], ret_cnt, ret_max, ret_max2, n, m, tmp, cnt_room[2504];
int dx[4= {-1010};
int dy[4= {0-101};
 
int dfs(int y, int x, int cnt_idx)
{
  int cnt = 1;
  visited[y][x] = cnt_idx;
  for (int i = 0; i < 4; i++)
  {
    if (!(mp[y][x] & (1 << i)))
    {
      int ny = y + dy[i];
      int nx = x + dx[i];
      if (ny >= 0 && ny < (m) && nx >= 0 && nx < n && visited[ny][nx] == 0)
      {
        cnt += dfs(ny, nx, cnt_idx);
      }
    }
  }
  return cnt;
}
 
// mp값이 1인곳은 벽 or 못가는곳  // 0인 곳은 갈 수 있는 곳
int main()
{
  cin >> n >> m;
  for (int i = 0; i < m; i++)
  {
    for (int j = 0; j < n; j++)
    {
      cin >> mp[i][j];
    }
  }
 
  for (int i = 0; i < (m); i++)
  {
    for (int j = 0; j < (n); j++)
    {
      if (visited[i][j] == 0)
      {
        ret_cnt++;
        int cnt = dfs(i, j, ret_cnt);
        ret_max = max(cnt, ret_max);
        cnt_room[ret_cnt] = cnt;
      }
    }
  }
 
  for (int i = 0; i < m; i++)
  {
    for (int j = 0; j < n; j++)
    {
      if (j + 1 < n)
      {
        int a = visited[i][j];
        int b = visited[i][j + 1];
        if (a != b)
        {
          ret_max2 = max(ret_max2, cnt_room[a] + cnt_room[b]);
        }
      }
      if (i + 1 < m)
      {
        int a = visited[i][j];
        int b = visited[i + 1][j];
        if (a != b)
        {
          ret_max2 = max(ret_max2, cnt_room[a] + cnt_room[b]);
        }
      }
    }
  }
  cout << ret_cnt << "\n"
       << ret_max << "\n"
       << ret_max2;
}
 
cs
 

 

'백준 알고리즘(C++)' 카테고리의 다른 글

백준 14391번 종이 조각 ( C++ )  (0) 2024.08.30
백준 11723번 집합 ( C++ )  (0) 2024.08.30
백준 1094번 막대기 ( C++ )  (0) 2024.08.29
백준 1062번 가르침 ( C++ )  (0) 2024.08.29
백준 14890번 경사로 ( C++ )  (1) 2024.08.28