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
| #include <cstdio> #include <tuple> #include <deque> using namespace std; int N, M; int map[100][100]; bool visit[100][100]; int cnt[100][100]; int dx[4] = { -1, 1, 0, 0 }; int dy[4] = { 0, 0, -1 ,1 }; void Input() { scanf("%d %d", &N, &M); for (int i = 0; i < M; ++i) { for (int j = 0; j < N; ++j) { scanf("%1d", &map[i][j]); } } } void BFS() { deque <pair<int, int>> q; q.push_front({ 0, 0 }); visit[0][0] = true; while (!q.empty()) { int x, y; tie(x, y) = q.front(); q.pop_front(); for (int dir = 0; dir < 4; ++dir) { int d_x = x + dx[dir]; int d_y = y + dy[dir]; if (d_x == N - 1 && d_y == M - 1) { cnt[d_x][d_y] = cnt[x][y]; return; } if (d_x > -1 && d_y > -1 && d_x < M && d_y < N) { if (visit[d_x][d_y]) continue; if (map[d_x][d_y] == 1) { cnt[d_x][d_y] = cnt[x][y] + 1; q.push_back({ d_x, d_y }); } else { cnt[d_x][d_y] = cnt[x][y]; q.push_front({ d_x, d_y }); } visit[d_x][d_y] = true; } } } } int main() { Input(); BFS(); printf("%d\n", cnt[M - 1][N - 1]); return 0; }
|