Hello Ocean! ๐ŸŒผ

[๋ฐฑ์ค€/C++] 1405. ๋ฏธ์นœ ๋กœ๋ด‡ ๋ณธ๋ฌธ

Algorithm

[๋ฐฑ์ค€/C++] 1405. ๋ฏธ์นœ ๋กœ๋ด‡

bba_dda 2021. 8. 17. 21:58
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ 

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

 

1405๋ฒˆ: ๋ฏธ์นœ ๋กœ๋ด‡

์ฒซ์งธ ์ค„์— N, ๋™์ชฝ์œผ๋กœ ์ด๋™ํ•  ํ™•๋ฅ , ์„œ์ชฝ์œผ๋กœ ์ด๋™ํ•  ํ™•๋ฅ , ๋‚จ์ชฝ์œผ๋กœ ์ด๋™ํ•  ํ™•๋ฅ , ๋ถ์ชฝ์œผ๋กœ ์ด๋™ํ•  ํ™•๋ฅ ์ด ์ฃผ์–ด์ง„๋‹ค. N์€ 14๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์ž์—ฐ์ˆ˜์ด๊ณ ,  ๋ชจ๋“  ํ™•๋ฅ ์€ 100๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์ž

www.acmicpc.net

๋กœ๋ด‡์ด 4๋ฐฉํ–ฅ (๋™์„œ๋‚จ๋ถ)์œผ๋กœ ๊ฐ๊ฐ ์ด๋™ํ•  ํ™•๋ฅ ๊ณผ, ์ด๋™ ํšŸ์ˆ˜๊ฐ€ ์ฃผ์–ด์งˆ ๋•Œ 

๋กœ๋ด‡์ด ํ•œ ๋ฒˆ ๋ฐฉ๋ฌธํ•œ ๊ณณ์„ ๋‹ค์‹œ ๋ฐฉ๋ฌธ ํ•˜์ง€ ์•Š์„ ํ™•๋ฅ ์„ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค. 

ํ’€์ด

๊ฐ€๋Šฅํ•œ ๋ชจ๋“  ์ด๋™ ๊ฒฝ๋กœ๋ฅผ ํƒ์ƒ‰ํ•˜๋ฉด์„œ ์ด์ „์— ๋ฐฉ๋ฌธํ–ˆ๋˜ ์นธ์„ ๋‹ค์‹œ ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€ ์ด๋™๊ฒฝ๋กœ์˜ ํ™•๋ฅ ์„ ๊ตฌํ•ด์„œ ๋ชจ๋‘ ๋”ํ•˜๋ฉด ๋œ๋‹ค. 

DFS๋กœ ํ’€์—ˆ๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ๋Š”๋ฐ, ๋ฐฑํŠธ๋ž˜ํ‚น์ด๋ผ๊ณ  ํ•œ๋‹ค..? 

๋‚ด๊ฐ€ ์ดํ•ดํ•˜๊ธฐ๋กœ๋Š” N๋ฒˆ ์ด๋™ํ•˜๋Š” ๊ฑธ ํƒ์ƒ‰ํ•œ๋‹ค๊ณ  ํ•  ๋•Œ 

๋งค๋ฒˆ ๊ธธ์ด N๋งŒํผ ๋๊นŒ์ง€ ํƒ์ƒ‰ํ•˜๋ฉด DFS, ์ค‘๊ฐ„์— ํŠน์ • ์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜์ง€ ์•Š๋Š” case๋ฅผ ๋ฒ„๋ฆฌ๊ณ  ํƒ์ƒ‰ํ•˜์ง€ ์•Š๋Š” ๊ฒƒ์€ ๋ฐฑํŠธ๋ž˜ํ‚น์ด๋ผ๊ณ  ํ•˜๋Š” ๊ฒƒ ๊ฐ™๋‹ค. 

 

DFS๋กœ ํƒ์ƒ‰ํ•˜๋ฉด์„œ, ์ค‘๊ฐ„์— visited๋ฐฐ์—ด ๊ฐ’์ด 1์ธ ๊ณณ์„ ๋ฐฉ๋ฌธํ•˜๋ฉด ํƒ์ƒ‰์„ ์ข…๋ฃŒํ–ˆ๋‹ค. ์ด๋™์„ N๋ฒˆ ํ–ˆ์„ ๋•Œ, (N๋ฒˆ ๋™์•ˆ ์ค‘๋ณต ๋ฐฉ๋ฌธ์ด ์—†์—ˆ์Œ) ํ•ด๋‹น ์ด๋™ ๊ฒฝ๋กœ์˜ ํ™•๋ฅ ์„ result์— ๋”ํ–ˆ๋‹ค. 

 

์ฝ”๋“œ

#include <cstdio>
#include <iostream>

#define sc scanf
using namespace std;

bool visited[29][29]; // 14+1+14 = 29
int N;
double per[4];
int dr[4] = { 0,0,1,-1 }; // E W S N
int dc[4] = { 1,-1,0,0 };
double result = 0;
void DFS(int startR, int startC, int n, double p) {
	if (n == N) {
		result += p;
		return;
	}
	for (int i = 0;i < 4;i++) {
		int nextR = startR + dr[i];
		int nextC = startC + dc[i];

		if (visited[nextR][nextC]) continue;
		visited[nextR][nextC] = 1;	
		DFS(nextR, nextC, n + 1, p * per[i]);
		visited[nextR][nextC] = 0;
	}
}
int main() {
	sc("%d", &N);
	for (int i = 0;i < 4;i++) {
		sc("%lf", &per[i]);
		per[i] /= 100.0;
	}
	visited[14][14] = 1;
	DFS(14,14, 0, 1);
	printf("%.10lf\n", result);
	return 0;
}

๊ฒฐ๊ณผ 

๋ฐ˜์‘ํ˜•