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
- 후니의 쉽게 쓴 시스코 네트워킹
- 이분탐색
- swea
- java
- Kotlin
- dfs
- 완전탐색
- 그리디
- 플로이드-와샬
- 동적계획법
- 투 포인터
- 세그먼트 트리
- 시뮬레이션
- 알고리즘
- Network
- 백트래킹
- CS
- 에라토스테네스의 체
- JUnit 5
- BFS
- 유니온 파인드
- 백준
- 구현
- 문자열
- Effective Java
- 위상정렬
- 스택
- mst
- 프로그래머스
- 수학
Archives
반갑습니다!
[백준] 14500 테트로미노 본문
풀이
완전탐색으로 해결할 수 있는 문제이다. 폴리오미노를 잘 살펴보면 ㅜ
모양을 제외하고서는 한붓그리기로 그릴 수 있는 모양이다. 즉 DFS를 통해 탐색할 수 있는 모양이다. 따라서 백트래킹으로 사용해서 모든 경우를 다 확인하고, 확인하지 못한 ㅜ
모양만 따로 확인해주면 쉽게 해결할 수 있다.
코드
#include <iostream>
#include <algorithm>
using namespace std;
int n, m, ans;
int map[500][500];
bool visited[500][500];
const int dx[] = { -1, 0, 1, 0 }, dy[] = { 0, -1, 0, 1 };
void dfs(int x, int y, int cnt, int sum) {
if (cnt == 4) {
ans = max(ans, sum);
return;
}
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx < 0 || nx > m - 1 || ny < 0 || ny > n - 1) continue;
if (!visited[ny][nx]) {
visited[ny][nx] = true;
dfs(nx, ny, cnt + 1, sum + map[ny][nx]);
visited[ny][nx] = false;
}
}
}
// ㅜ 모양 블럭
void calculate_edge_case(int x, int y) {
// ㅗ
if (1 <= x && x <= m - 2 && 1 <= y && y <= n - 1) ans = max(ans, map[y][x - 1] + map[y][x] + map[y][x + 1] + map[y - 1][x]);
// ㅓ
if (1 <= x && x <= m - 1 && 1 <= y && y <= n - 2) ans = max(ans, map[y][x - 1] + map[y][x] + map[y + 1][x] + map[y - 1][x]);
// ㅜ
if (1 <= x && x <= m - 1 && 0 <= y && y <= n - 2) ans = max(ans, map[y][x - 1] + map[y][x] + map[y][x + 1] + map[y + 1][x]);
// ㅏ
if (0 <= x && x <= m - 2 && 1 <= y && y <= n - 2) ans = max(ans, map[y][x + 1] + map[y][x] + map[y + 1][x] + map[y - 1][x]);
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cin >> map[i][j];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
visited[i][j] = true;
dfs(j, i, 1, map[i][j]);
visited[i][j] = false;
calculate_edge_case(j, i);
}
}
cout << ans << '\n';
return 0;
}
'알고리즘 문제 풀이' 카테고리의 다른 글
[백준] 9655 돌 게임 (0) | 2020.04.29 |
---|---|
[백준] 16197 두 동전 (0) | 2020.04.29 |
[백준] 14499 주사위 굴리기 (0) | 2020.04.29 |
[프로그래머스] 튜플 (0) | 2020.04.29 |
[프로그래머스] 단체사진 찍기 (0) | 2020.04.29 |