BOJ ๋ฌธ์ œ ๋ณด๊ธฐ

1. ๋ฌธ์ œ

BFS๋กœ ํ’€ ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ œ๋‹ค.

  1. ์ตœ์†Œ ์ด๋™ ํšŸ์ˆ˜๋ฅผ ๊ตฌํ•จ
  2. ์ด๋™ํ•  ๊ฒฝ๋กœ๊ฐ€ (r-2,c-1), (r-2,c+1), (r,c-2), (r,c+2), (r+2,c-1), (r+2,c+1) ์ค‘ ํ•œ ์นธ์„ ๊ณ ๋ฅด๋Š” ๊ฒƒ์ž„
  3. ์‹œ์ž‘์ ๊ณผ ๋„์ฐฉ์  ์œ„์น˜ ์ œ๊ณต
  4. ์ฒด์ŠคํŒ์˜ ํฌ๊ธฐ ์ œํ•œ



2. ํ•ด๊ฒฐ ๊ณผ์ •

BFS์„ ํ™œ์šฉํ•œ ๋ฏธ๋กœ ํƒ์ƒ‰ ์œ ํ˜•๊ณผ ํฐ ์ฐจ์ด ์—†์ด ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค.

BFS/DFS ๋ฌธ์ œ ํ•ด๊ฒฐ ์œ ํ˜•

  • ์ตœ์†Œ ํšŸ์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ
  • ํ•˜๋‚˜์˜ ์ •์ ์—์„œ ์‹œ์ž‘ํ•ด ์—ฐ๊ฒฐ๋œ ๋ชจ๋“  ์ •์  ๋ฐฉ๋ฌธ

์ตœ์•…์˜ ๊ฒฝ์šฐ ๋ชจ๋“  ์ฒด์ŠคํŒ์˜ ์นธ์„ ๋ฐฉ๋ฌธํ•ด์•ผ ํ•˜๋ฏ€๋กœ ์ „์ฒด ์ •์ ์˜ ๊ฐœ์ˆ˜๋Š” $N^{2}$, BFS๊ฐ€ ์ •์ ์„ ํ•œ ๋ฒˆ์”ฉ ๊ณ„์‚ฐํ•˜๋ฉด ์‹œ๊ฐ„ ๋ณต์žก๋„๋Š” $O(N^{2})$์ด ๋œ๋‹ค.

N์˜ ์ตœ๋Œ€ ํฌ๊ธฐ๊ฐ€ 200์ด๋ฏ€๋กœ ์ œํ•œ ์‹œ๊ฐ„ ์•ˆ์— ์ถฉ๋ถ„ํžˆ ์ตœ์  ๊ฒฝ๋กœ๋ฅผ ํƒ์ƒ‰ํ•  ์ˆ˜ ์žˆ๋‹ค.


๋ฏธ๋กœ ํƒ์ƒ‰ ๋ฌธ์ œ์™€ ๋‹ค๋ฅธ์ 

  • x, y ์ด๋™ ๋ฒ”์œ„
    • ๋ฐ์Šค๋‚˜์ดํŠธ์— ๋งž๊ฒŒ ์ƒ๋Œ€ ์œ„์น˜ dx, dy ๋ฐฐ์—ด ํ™•์žฅ
  • ์ด๋™ํ•  ์ˆ˜ ์—†๋Š” ๊ฒฝ์šฐ -1 ์ถœ๋ ฅ



3. ์ฝ”๋“œ

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
#include <stdio.h>
#include <iostream>
#include <queue>
using namespace std;

int n, r1, c1, r2, c2, x, y, nx, ny, i;
int dx[] = { -2, -2, 0, 0, 2, 2 };
int dy[] = { -1, 1, -2, 2, -1, 1 };
int dist[200][200] = { 0, };
queue<pair<int, int>> q;

int main()
{
	scanf("%d %d %d %d %d", &n, &r1, &c1, &r2, &c2);
	q.push(make_pair(r1, c1));

	while (!q.empty())
	{
		x = q.front().first;
		y = q.front().second;
		q.pop();

		for (i = 0; i < 6; i++)
		{
			nx = x + dx[i];
			ny = y + dy[i];

			if (nx < 0 || nx >= n || ny < 0 || ny >= n) continue;
			if (dist[nx][ny] == 0)
			{
				q.push(make_pair(nx, ny));
				dist[nx][ny] = dist[x][y] + 1;
			}
		}
	}
	if (dist[r2][c2] == 0) printf("-1");
	else printf("%d", dist[r2][c2]);
}

image



4. ์ƒ๊ฐ ์ •๋ฆฌ

์ฝ”๋“œ ์ž‘์„ฑ๋ณด๋‹ค ๋ฌธ์ œ๋ฅผ ์ œ๋Œ€๋กœ ๊ทธ๋ ค๋ณด๋Š”๋ฐ ์‹œ๊ฐ„์„ ๋” ์ผ๋‹ค. ๋ฌธ์ œ์— ๋‚ฏ์„  ์ •๋ณด๊ฐ€ ๋ณด์ด๋ฉด ์œ ๋… ๋‹นํ™ฉํ•ด ์ดํ•ดํ•˜๋Š”๋ฐ ์˜ค๋ž˜ ๊ฑธ๋ฆฐ๋‹ค. ์ƒˆ๋กœ ๋“ค์–ด์˜ค๋Š” ์ •๋ณด๋ฅผ ๋ฌด์ž‘์ • ์ฐจ๋‹จํ•˜๋ ค ํ•˜์ง€ ๋ง๊ณ  ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ง€์‹๊ณผ ์ž˜ ์—ฎ์–ด๋ณด์ž.

ํŠนํžˆ BFS ์‹ค๋ฒ„ ๋ฌธ์ œ๋Š” ๊ธฐ๋ณธ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ฝ”๋“œ์˜ ํฐ ๋ณ€ํ˜• ์—†์ด ์‰ฝ๊ฒŒ ๋ฌธ์ œ๋ฅผ ํ’€ ์ˆ˜ ์žˆ๋‹ค. ์‹ค๋ฒ„ ๋ฌธ์ œ๋กœ ๊ธฐ๋ณธ๊ธฐ๋ฅผ ๋‹ค์ง€๊ณ  ๋‚˜์„œ ๋‹ค์–‘ํ•œ ํ™•์žฅ ๋ฌธ์ œ๋„ ๋„์ „ํ•ด๋ณด์ž.๐Ÿฅฐ

Leave a comment