Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- dfs
- 유니온 파인드
- BFS
- 에라토스테네스의 체
- 위상정렬
- 수학
- 투 포인터
- 알고리즘
- 완전탐색
- 시뮬레이션
- 이분탐색
- 플로이드-와샬
- 문자열
- 후니의 쉽게 쓴 시스코 네트워킹
- 백트래킹
- JUnit 5
- 프로그래머스
- mst
- Kotlin
- Effective Java
- 백준
- 세그먼트 트리
- swea
- Network
- 동적계획법
- 그리디
- java
- 구현
- 스택
- CS
Archives
반갑습니다!
[백준] 1926 그림 본문
풀이
카카오 프렌즈 컬러링 북과 동일한 문제이다. DFS와 BFS로 모두 풀 수 있다.
이번엔 DFS로 풀어보았다.
코드
#include <iostream>
#include <stack>
#include <vector>
#include <algorithm>
using namespace std;
int n, m;
vector<vector<int>> paint;
vector<vector<bool>> visited;
const int dx[] = { -1, 0, 1, 0 }, dy[] = { 0, -1, 0, 1 };
bool inRange(int x, int y) {
return (0 <= x && x < m) && (0 <= y && y < n);
}
int dfs(int x, int y) {
int cnt = 0;
int v = paint[y][x];
visited[y][x] = true;
stack<pair<int, int>> s;
s.push({ x, y });
while (!s.empty()) {
pair<int, int> cur = s.top();
s.pop();
cnt++;
for (int i = 0; i < 4; i++) {
int nx = cur.first + dx[i];
int ny = cur.second+ dy[i];
if (inRange(nx, ny) && !visited[ny][nx] && paint[ny][nx] == v) {
s.push({ nx, ny });
visited[ny][nx] = true;
}
}
}
return cnt;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m;
int paint_cnt = 0;
int max_paint = 0;
paint = vector<vector<int>>(n, vector<int>(m));
visited = vector<vector<bool>>(n, vector<bool>(m, false));
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cin >> paint[i][j];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (!visited[i][j] && paint[i][j] != 0) {
max_paint = max(max_paint, dfs(j, i));
paint_cnt++;
}
}
}
cout << paint_cnt << '\n' << max_paint << '\n';
return 0;
}
'알고리즘 문제 풀이' 카테고리의 다른 글
[프로그래머스] 문자열 내 마음대로 정렬하기 (0) | 2020.04.04 |
---|---|
[프로그래머스] 정수 내림차순으로 배치하기 (0) | 2020.04.04 |
[프로그래머스] 괄호 변환 (0) | 2020.04.03 |
[프로그래머스] 짝지어 제거하기 (0) | 2020.04.03 |
[프로그래머스] JadenCase 문자열 만들기 (0) | 2020.04.03 |