#include <iostream>
#include <queue>
#include <string>

using namespace std;

int N, M;

string board[101];
int visited[101][101];

int dr[4] = {-1,1,0,0};
int dc[4] = {0,0,-1,1};

int main() {

    cin >> N >> M;

    for (int i = 0; i < N; i++) {
        cin >> board[i];
    }

    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
            visited[i][j] = -1;
        }
    }

    queue<pair<int,int>> q;

    q.push({0,0});
    visited[0][0] = 0;

    while (!q.empty()) {

        int r = q.front().first;
        int c = q.front().second;
        q.pop();

        // 도착
        if (r == N-1 && c == M-1) {
            cout << visited[r][c] << "\n";
            return 0;
        }

        for (int i = 0; i < 4; i++) {

            int nr = r + dr[i];
            int nc = c + dc[i];

            if (nr >= 0 && nr < N &&
                nc >= 0 && nc < M) {

                if (board[nr][nc] == '0' &&
                    visited[nr][nc] == -1) {

                    visited[nr][nc]
                        = visited[r][c] + 1;

                    q.push({nr,nc});
                }
            }
        }
    }

    cout << -1 << "\n";
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: