https://school.programmers.co.kr/learn/courses/30/lessons/1829
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
|
#include <vector>
#include <map>
#include <iostream>
using namespace std;
vector<vector<bool>> visitNode;
int sizeOfRow;
int sizeOfColumn;
enum direction
{
UP,
DOWN,
LEFT,
RIGHT
};
int DFS(int x, int y, vector<vector<int>>& pictures, int& size)
{
visitNode[x][y] = true;
for (int i = 0; i < 4; i++)
{
int nextX = x;
int nextY = y;
//방향 상하좌우 검사
switch (i)
{
case UP:
nextY--;
break;
case DOWN:
nextY++;
break;
case LEFT:
nextX--;
break;
case RIGHT:
nextX++;
break;
}
//다음에 방문할 노드에 대해...
//인덱스가 영역을 벗어나면 continue
if (nextX < 0 || nextY < 0 || nextX >= sizeOfRow || nextY >= sizeOfColumn)
continue;
//현재 검사중인 노드와 다음에 검사할 노드의 색이 다르면 continue
if (pictures[x][y] != pictures[nextX][nextY])
continue;
//이미 방문한 노드이면 continue
if (visitNode[nextX][nextY] == true)
continue;
size++;
//다음 노드로 넘어가서 다시 검사한다.
DFS(nextX, nextY, pictures, size);
}
return size;
}
vector<int> solution(int m, int n, vector<vector<int>> picture) {
int areaCount = 0;
int maxSize = 0;
sizeOfRow = m;
sizeOfColumn = n;
vector<vector<bool>> initializedVisitNode(sizeOfRow, vector<bool>(sizeOfColumn));
visitNode = initializedVisitNode;
for (int i = 0; i < picture.size(); i++)
{
for (int j = 0; j < picture[0].size(); j++)
{
//한번 방문한 곳은 검사 안함
if (visitNode[i][j] == 1)
continue;
//색칠되지 않은 곳은 검사 안함
if (picture[i][j] == 0)
continue;
//영역 넓이 초기화
int size = 1;
int sizeOfOneArea = DFS(i, j, picture, size);
if (maxSize < sizeOfOneArea)
maxSize = sizeOfOneArea;
//한번 돌면, 해당 색깔의 영역은 모두 방문한 것
areaCount++;
}
}
vector<int> answer(2);
answer[0] = areaCount;
answer[1] = maxSize;
return answer;
}
|
cs |
'프로그래머스 - 내 풀이 > 프로그래머스 Lv2' 카테고리의 다른 글
프로그래머스/연속된 부분 수열의 합 (0) | 2023.04.15 |
---|---|
프로그래머스/괄호 회전하기 (0) | 2023.04.14 |
프로그래머스/H-Index (0) | 2022.12.07 |
프로그래머스 / KAKAO BLIND RECRUITMENT / 오픈채팅방 (0) | 2022.02.11 |
프로그래머스 / 월간 코드 챌린지 시즌1 / 삼각 달팽이도움말 (0) | 2021.04.07 |