-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2178.cpp
More file actions
70 lines (62 loc) · 1.28 KB
/
2178.cpp
File metadata and controls
70 lines (62 loc) · 1.28 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <iostream>
#include <algorithm>
#include <queue>
#include <tuple>
int map[100][100];
int visit[100][100];
std::queue<std::tuple<int, int, int> > queue;
int dy[] = {1, -1, 0, 0};
int dx[] = {0, 0, 1, -1};
int bfs(int init_i, int init_j, int N, int M)
{
queue.push(std::make_tuple(init_i, init_j, 1));
visit[init_i][init_j] = true;
while (!queue.empty())
{
std::tuple<int, int, int> next = queue.front();
queue.pop();
if (std::get<0>(next) == N - 1 && std::get<1>(next) == M - 1)
return std::get<2>(next);
for (int i = 0; i < 4; ++i)
{
int ny = std::get<0>(next) + dy[i];
int nx = std::get<1>(next) + dx[i];
if (ny < 0 || ny >= N || nx < 0 || nx >= M)
continue ;
if (visit[ny][nx] || map[ny][nx] != 1)
continue;
visit[ny][nx] = true;
queue.push(std::make_tuple(ny, nx, std::get<2>(next) + 1));
}
}
return 0;
}
int main()
{
int N, M;
std::cin >> N >> M;
for (int i = 0; i < N; ++i)
{
std::string line;
std::cin >> line;
for (int j = 0; j < M; ++j)
{
map[i][j] = line[j] - '0';
}
}
for (int i = 0; i < N; ++i)
{
for (int j = 0; j < M; ++j)
{
if (map[i][j] == 1 && visit[i][j] == false)
{
int result = bfs(i, j, N, M);
if (result != 0)
{
std::cout << result << '\n';
return 0;
}
}
}
}
}