#include<cstdio> #include<queue> #define MAX 1001 usingnamespacestd; int n, m; intmap[MAX][MAX]; int path[MAX][MAX][2]; // 벽을 안부순 경로, 벽을 부순 경로 int dx[4] = { -1, 1, 0, 0 }; int dy[4] = { 0, 0, -1, 1 }; structINFO { int r, c; bool break_wall = false; }; intbfs(){ queue<INFO> q; q.push({ 0, 0, false }); path[0][0][0] = 1; while (!q.empty()) { int r = q.front().r; int c = q.front().c; bool bw = q.front().break_wall; q.pop(); if (r == n - 1 && c == m - 1) return path[r][c][bw]; for (int i = 0; i < 4; ++i) { int x = r + dx[i]; int y = c + dy[i]; if (x > -1 && y > -1 && x < n && y < m) { if (path[x][y][bw]) continue; if (map[x][y] == 0) { path[x][y][bw] = path[r][c][bw] + 1; q.push({ x, y, bw }); } elseif(map[x][y] == 1 && bw == 0) { path[x][y][1] = path[r][c][bw] + 1; q.push({ x, y, true }); } } } } return-1; } intmain(){ scanf("%d %d", &n, &m); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { scanf("%1d", &map[i][j]); } } printf("%d\n", bfs()); return0; }