forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path11.cpp
More file actions
52 lines (47 loc) ยท 1.53 KB
/
11.cpp
File metadata and controls
52 lines (47 loc) ยท 1.53 KB
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
48
49
50
51
52
#include <bits/stdc++.h>
using namespace std;
int n, m;
int graph[201][201];
// ์ด๋ํ ๋ค ๊ฐ์ง ๋ฐฉํฅ ์ ์ (์, ํ, ์ข, ์ฐ)
int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, -1, 1};
int bfs(int x, int y) {
// ํ(Queue) ๊ตฌํ์ ์ํด queue ๋ผ์ด๋ธ๋ฌ๋ฆฌ ์ฌ์ฉ
queue<pair<int, int> > q;
q.push({x, y});
// ํ๊ฐ ๋น ๋๊น์ง ๋ฐ๋ณตํ๊ธฐ
while(!q.empty()) {
int x = q.front().first;
int y = q.front().second;
q.pop();
// ํ์ฌ ์์น์์ 4๊ฐ์ง ๋ฐฉํฅ์ผ๋ก์ ์์น ํ์ธ
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
// ๋ฏธ๋ก ์ฐพ๊ธฐ ๊ณต๊ฐ์ ๋ฒ์ด๋ ๊ฒฝ์ฐ ๋ฌด์
if (nx < 0 || nx >= n || ny < 0 || ny >= m) continue;
// ๋ฒฝ์ธ ๊ฒฝ์ฐ ๋ฌด์
if (graph[nx][ny] == 0) continue;
// ํด๋น ๋
ธ๋๋ฅผ ์ฒ์ ๋ฐฉ๋ฌธํ๋ ๊ฒฝ์ฐ์๋ง ์ต๋จ ๊ฑฐ๋ฆฌ ๊ธฐ๋ก
if (graph[nx][ny] == 1) {
graph[nx][ny] = graph[x][y] + 1;
q.push({nx, ny});
}
}
}
// ๊ฐ์ฅ ์ค๋ฅธ์ชฝ ์๋๊น์ง์ ์ต๋จ ๊ฑฐ๋ฆฌ ๋ฐํ
return graph[n - 1][m - 1];
}
int main(void) {
// N, M์ ๊ณต๋ฐฑ์ ๊ธฐ์ค์ผ๋ก ๊ตฌ๋ถํ์ฌ ์
๋ ฅ ๋ฐ๊ธฐ
cin >> n >> m;
// 2์ฐจ์ ๋ฆฌ์คํธ์ ๋งต ์ ๋ณด ์
๋ ฅ ๋ฐ๊ธฐ
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
scanf("%1d", &graph[i][j]);
}
}
// BFS๋ฅผ ์ํํ ๊ฒฐ๊ณผ ์ถ๋ ฅ
cout << bfs(0, 0) << '\n';
return 0;
}