[BOJ] #7562 λμ΄νΈμ μ΄λ
μκ° μ ν | λ©λͺ¨λ¦¬ μ ν | μ λ΅ λΉμ¨ |
1 μ΄ | 256 MB | 43.859% |
7562λ²: λμ΄νΈμ μ΄λ
λ¬Έμ 체μ€ν μμ ν λμ΄νΈκ° λμ¬μ Έ μλ€. λμ΄νΈκ° ν λ²μ μ΄λν μ μλ μΉΈμ μλ κ·Έλ¦Όμ λμμλ€. λμ΄νΈκ° μ΄λνλ €κ³ νλ μΉΈμ΄ μ£Όμ΄μ§λ€. λμ΄νΈλ λͺ λ² μμ§μ΄λ©΄ μ΄ μΉΈμΌλ‘ μ΄λν μ μμκΉ? μ λ ₯ μ λ ₯μ 첫째 μ€μλ ν μ€νΈ μΌμ΄μ€μ κ°μκ° μ£Όμ΄μ§λ€. κ° ν μ€νΈ μΌμ΄μ€λ μΈ μ€λ‘ μ΄λ£¨μ΄μ Έ μλ€. 첫째 μ€μλ 체μ€νμ ν λ³μ κΈΈμ΄ l(4 ≤ l ≤ 300)μ΄ μ£Όμ΄μ§λ€. 체μ€νμ ν¬κΈ°λ l × lμ΄λ€. 체μ€νμ κ° μΉΈμ λ μμ μ {0, ...
www.acmicpc.net
λ¬Έμ
체μ€ν μμ λμ΄νΈλ₯Ό λͺ λ² μμ§μ¬ νμ¬ μμΉμμ λͺ©μ μ§κΉμ§ κ° μ μλμ§ ν μλ₯Ό μΆλ ₯νλ λ¬Έμ μ΄λ€.
λμ΄νΈμ μ΄λμ μΈλ±μ€λ‘ νννμ¬ dx, dy λΌλ λ°°μ΄μ μ μ₯ν΄λμκ³ λ°λ³΅λ¬Έμ λλ©΄μ ν΄λΉ μΈλ±μ€μμ λͺ λ²μ§Έ μ΄λμ΄μλμ§λ₯Ό chk[][]μ μ μ₯νκ³ , ν΄λΉ μΈλ±μ€κ° λͺ©μ μ§μ κ°λ€λ©΄ ν¨μλ₯Ό λλ΄κ³ λ΅μ μΆλ ₯νλ€.
μνμ°©μ€
κ³μ λ§λλ° μ νλ¦΄κΉ νλλ dx λ₯Ό κ³μ int dx[] = { -2,-1,1,2,2,1,-1,-1 } λ‘ μ°κ³ μμλ€. μ λλ‘ κ³ μΉκ³ μ±κ³΅. λ무λλ ν무νλ€. 미리미리 μ€μνμ§ μκ² κΌΌκΌΌνκ² νμΈνμ.
λ©λͺ¨λ¦¬ | μκ° |
2352 KB | 20 ms |
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
39
40
41
42
43
44
45
46
47
|
#include<iostream>
#include<string.h>
#include<queue>
using namespace std;
typedef pair<int, int> p;
int dx[] = { -2,-1,1,2,2,1,-1,-2 }, dy[] = { 1,2,2,1,-1,-2,-2,-1 };
int t, n, chk[305][305], ans;
p start, destination;
void bfs(int x, int y) {
if (x == destination.first && y == destination.second) {
ans = 0;
return;
}
queue <p> q;
q.push({ x, y });
chk[x][y] = 0;
while (!q.empty()) {
int r = q.front().first, c = q.front().second;
q.pop();
for (int i = 0; i < 8; i++) {
int nr = r + dx[i], nc = c + dy[i];
if (nr < 0 || nr >= n || nc < 0 || nc >= n) continue;
if (chk[nr][nc] > 0) continue;
chk[nr][nc] = chk[r][c] + 1;
if (nr == destination.first && nc == destination.second) {
ans = chk[nr][nc]; return;
}
q.push({ nr, nc });
}
}
}
int main() {
scanf("%d", &t);
while (t--) {
scanf("%d", &n);
scanf("%d %d %d %d", &start.first, &start.second, &destination.first, &destination.second);
memset(chk, -1, sizeof(chk));
ans = 0;
bfs(start.first, start.second);
printf("%d\n", ans);
}
return 0;
}
|
cs |
μ°Έκ³ μ¬ν
for λ¬Έμ μλμ κ°μ΄ μμ±νκ² λλ©΄ μ½λλ μ‘°κΈ μ€μ΄λ€μ§ λͺ°λΌλ μκ°μ 4 ms λ§νΌ μ¦κ°νλ€!
1
2
3
4
5
6
7
8
9
10
11
|
for (int i = 0; i < 8; i++) {
int nr = r + dx[i], nc = c + dy[i];
if (nr >= 0 && nr < n && nc >= 0 && nc < n && chk[nr][nc] < 0) {
chk[nr][nc] = chk[r][c] + 1;
if (nr == destination.first && nc == destination.second) {
ans = chk[nr][nc]; return;
}
q.push({ nr, nc });
}
}
|
cs |