Buggy python submission (verdict: Runtime Error):
from queue import Queue
from collections import defaultdict
try:
    d = [[1, 0], [-1, 0], [0, 1], [0, -1]]
    
    H, W, N = map(int, input().split())
    
    G = []
    
    sx = sy = 0
    for i in range(H):
        G.append(input())
        for j, c in enumerate(G[i]):
            if c == 'S':
                sx, sy = i, j
    
    Q = Queue()
    Q.put((sx, sy, 0))
    visited = defaultdict(lambda: defaultdict(lambda: False))
    visited[sx][sy] = True
    
    target = 1

    while not Q.empty():
        x, y, step = Q.get()
        if G[x][y] == str(target):
            visited.clear()
            visited[x][y] = True
            while not Q.empty():
                Q.get()
            target += 1
            if target == N + 1:
                print(step)
                break
        for dx, dy in d:
            nx, ny = x + dx, y + dy
            if 0 <= nx < H and 0 <= ny < W and G[nx][ny] != 'X':
                if not visited[nx][ny]:
                    visited[nx][ny] = True
                    Q.put((nx, ny, step + 1))
except BaseException as e:
    print(e)




Fixed submission:
from collections import deque, defaultdict

d = [[1, 0], [-1, 0], [0, 1], [0, -1]]

H, W, N = map(int, input().split())

G = []

sx = sy = 0
for i in range(H):
    G.append(input())
    for j, c in enumerate(G[i]):
        if c == 'S':
            sx, sy = i, j


Q = deque()
Q.append((sx, sy, 0))
visited = defaultdict(lambda: defaultdict(int))
visited[sx][sy] = 1

target = '1'

while len(Q):
    x, y, step = Q.popleft()
    if G[x][y] == target:
        visited.clear()
        Q.clear()
        target = str(int(target) + 1)
        if target == str(N + 1):
            print(step)
            break
    for dx, dy in d:
        nx, ny = x + dx, y + dy
        if 0 <= nx < H and 0 <= ny < W and G[nx][ny] != 'X':
            if not visited[nx][ny]:
                visited[nx][ny] = 1
                Q.append((nx, ny, step + 1))

Buggy python submission (verdict: Runtime Error):
from queue import Queue
from collections import defaultdict
try:
    d = [[1, 0], [-1, 0], [0, 1], [0, -1]]
    H, W, N = map(int, input().split())
    G = []
    sx = sy = 0
    for i in range(H):
        G.append(input())
        for j, c in enumerate(G[i]):
            if c == 'S':
                sx, sy = i, j

    Q = Queue()
    Q.put((sx, sy, 0))
    visited = defaultdict(lambda: defaultdict(lambda: 0))
    # visited = [[False for _ in range(W)] for _ in range(H)]
    visited[sx][sy] = True
    target = 1

    while not Q.empty():
        x, y, step = Q.get()
        if G[x][y] == str(target):
            # visited = [[False for _ in range(W)] for _ in range(H)]
            # visited.clear()
            target += 1
            visited[x][y] = target
            while not Q.empty():
                Q.get()
            if target == N + 1:
                print(step)
                break
        for dx, dy in d:
            nx, ny = x + dx, y + dy
            if 0 <= nx < H and 0 <= ny < W and G[nx][ny] != 'X':
                if visited[nx][ny] != target:
                    visited[nx][ny] = target
                    Q.put((nx, ny, step + 1))

except BaseException as e:
    print(e)




Fixed submission:
from collections import deque, defaultdict

d = [[1, 0], [-1, 0], [0, 1], [0, -1]]

H, W, N = map(int, input().split())

G = []

sx = sy = 0
for i in range(H):
    G.append(input())
    for j, c in enumerate(G[i]):
        if c == 'S':
            sx, sy = i, j


Q = deque()
Q.append((sx, sy, 0))
visited = defaultdict(lambda: defaultdict(int))
visited[sx][sy] = 1

target = '1'

while len(Q):
    x, y, step = Q.popleft()
    if G[x][y] == target:
        visited.clear()
        Q.clear()
        target = str(int(target) + 1)
        if target == str(N + 1):
            print(step)
            break
    for dx, dy in d:
        nx, ny = x + dx, y + dy
        if 0 <= nx < H and 0 <= ny < W and G[nx][ny] != 'X':
            if not visited[nx][ny]:
                visited[nx][ny] = 1
                Q.append((nx, ny, step + 1))