Point πŸ’‘


My Solution


import sys
from collections import deque

n, m = map(int, sys.stdin.readline().split())
graph = []

for _ in range(n):
    raw = list(map(int, list(sys.stdin.readline().rstrip())))
    graph.append(raw)

# 쀑간에 벽을 단 ν•œλ²ˆλ§Œ λΆ€μˆ  수 μžˆμœΌλ―€λ‘œ 벽을 λΆ€μ‰ˆλŠ”μ§€ μ—¬λΆ€λ₯Ό 3차원 ν–‰λ ¬λ‘œ ν‘œν˜„
# zκ°€ 0이면 벽을 νŒŒκ΄΄ν•  수 있고, zκ°€ 1이면 λΆˆκ°€λŠ₯
# 벽을 λΆ€μˆ˜μ§€ μ•Šμ€ 경둜, 벽을 λΆ€μˆœ 경둜
visited = [[[0, 0] for _ in range(m)] for _ in range(n)]

# 처음 μ‹œμž‘ λ…Έλ“œ ν¬ν•¨μ΄λ―€λ‘œ 벽을 λΆ€μˆ˜μ§€μ•Šμ€ κ²½λ‘œμ— 개수 1둜 μ„€μ •
visited[0][0][0] = 1

dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]

# μ΅œλ‹¨κ²½λ‘œ -> bfs
def bfs(x, y, z):
    queue = deque([(x, y, 0)])

    while queue:
        cur_x, cur_y, cnt = queue.popleft()

        # 끝 점에 λ„λ‹¬ν•˜λ©΄ 이동 횟수λ₯Ό 좜λ ₯
        if cur_x == n-1 and cur_y == m-1 :
            return visited[cur_x][cur_y][cnt]

        for i in range(4):
            nx, ny = cur_x + dx[i], cur_y + dy[i]
            if 0 <= nx < n and 0 <= ny < m:
                # λ‹€μŒ 이동할 곳이 벽이 μ•„λ‹ˆκ³ , 아직 ν•œλ²ˆλ„ λ°©λ¬Έν•˜μ§€ μ•Šμ€ 곳이면
                # λ²½ 파괴기회λ₯Ό ν•œλ²ˆ μ‚¬μš©ν•˜λ©΄ 계속 cntλŠ” 1 (indexκ°€ 1인 곳에 계속 개수 μ €μž₯)
                if graph[nx][ny] == 0 and visited[nx][ny][cnt] == 0 :
                    visited[nx][ny][cnt] = visited[cur_x][cur_y][cnt] + 1
                    queue.append((nx, ny, cnt))

                # λ‹€μŒ 이동할 곳이 벽이고, λ²½ 파괴기회λ₯Ό μ‚¬μš©ν•˜μ§€ μ•Šμ€ 경우
                elif graph[nx][ny] == 1 and cnt == 0 :
                    # 벽을 λΆ€μˆœ κ²½λ‘œμ— 개수 μΆ”κ°€
                    visited[nx][ny][1] = visited[cur_x][cur_y][0] + 1
                    queue.append((nx, ny, 1))

    return -1

print(bfs(0, 0, 0))

BackTracking Solution (Time-Over)

# μ—°κ΅¬μ†Œ λ¬Έμ œμ™€ λΉ„μŠ·ν•˜κ²Œ 풀이

from collections import deque
import sys
input = sys.stdin.readline
def bfs():
    queue = deque()
    trial = [item[:] for item in grid]

    queue.append([0, 0])

    while queue:
        if trial[n-1][m-1] != 0:
            break
        y, x = queue.popleft()

        for i in range(4):
            ny = y + dy[i]
            nx = x + dx[i]

            if ny <= -1 or ny >= n or nx <= -1 or nx >= m:
                continue
            if trial[ny][nx] == 0:
                trial[ny][nx] = trial[y][x] + 1
                queue.append([ny, nx])

    global answer
    if trial[n-1][m-1] >= 1:
        answer = min(answer, trial[n-1][m-1])

def breakWall():
    for i in range(n):
        for j in range(m):
            if grid[i][j] == 1:
                grid[i][j] = 0
                bfs()
                grid[i][j] = 1

n, m = map(int, input().split())
grid = []
dy = [-1, 1, 0, 0]
dx = [0, 0, -1, 1]

for _ in range(n):
    grid.append(list(map(int, input().strip())))

answer = float("inf")

bfs()
breakWall()

if n == 1 and m == 1:
    print(1)
elif answer == float("inf"):
    print(-1)
else:
    print(answer+1)