문제 출처: https://www.acmicpc.net/problem/1405
Solution
- 모든 경로 탐색하는 문제, DFS하면서 해당 경로 갈 확률을 더해하고, 이미 visit한 곳은 simple path가 아니기 때문에 제외한다.
Point
- DFS return할 때 다른 경로로 해당 칸 갈 경우도 고려해야하므로 visit을 false로 해줘야한다.
- 출력 양식을 문제 오차 범위 조건에 맞게 잘 해줘야 한다.
#include <iostream>
#include <cstring>
using namespace std;
int N;
double p[4]; //pe, pw, ps, pn
bool visited[30][30];
int dx[4] = { 1, -1, 0, 0 }; //E, W, S, N
int dy[4] = { 0, 0, -1, 1 };
void input() {
cin >> N;
for (int i = 0; i < 4; i++) {
int x;
cin >> x;
p[i] = x / (double)100;
}
}
double dfs(int cx, int cy, int depth) {
if (depth == N) return 1.0;
visited[cx][cy] = true;
double result = 0.0;
for (int i = 0; i < 4; i++) {
int nx = cx + dx[i];
int ny = cy + dy[i];
if (visited[nx][ny]) continue;
result += p[i] * dfs(nx, ny, depth+1);
}
visited[cx][cy] = false;
return result;
}
int main()
{
input();
printf("%.10lf\n", dfs(14, 14, 0));
}
'알고리즘 ·코딩 공부 > 백준 온라인 문제 풀이' 카테고리의 다른 글
[DFS] BJ16986 인싸들의 가위바위보 (0) | 2019.03.20 |
---|---|
[DFS] BJ17070 파이프 옮기기 1 (0) | 2019.03.20 |
[BFS, DFS] BJ2468 안전 영역 (0) | 2019.02.14 |
[DFS] BJ2668 숫자 고르기 (0) | 2019.02.14 |
[시뮬레이션] BJ2174 로봇시뮬레이션 (0) | 2019.02.14 |