#include <iostream>
#include <queue>
#define MAP_SIZE 105
using namespace std;
struct Coord {
int row;
int col;
};
int N, M;
char MAP[MAP_SIZE][MAP_SIZE];
int visited[MAP_SIZE][MAP_SIZE];
int dr[] = { 0, 0, -1, 1 };
int dc[] = { -1, 1, 0, 0 };
void bfs(int s_row, int s_col, int e_row, int e_col)
{
queue<Coord> nowQ;
nowQ.push({ s_row, s_col });
while (!nowQ.empty())
{
if (s_row == e_row && s_col == e_col) return;
Coord now = nowQ.front();
nowQ.pop();
for (int i = 0; i < 4; i++)
{
int next_row = now.row + dr[i];
int next_col = now.col + dc[i];
if (next_row < 0 || next_col < 0 || next_row >= N || next_col >= M) continue;
if (MAP[next_row][next_col] == 0) continue;
if (visited[next_row][next_col] != 0) continue;
visited[next_row][next_col] = visited[now.row][now.col] + 1;
nowQ.push({ next_row, next_col });
}
}
}
int main()
{
cin >> N >> M;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M; j++)
{
char input;
cin >> input;
MAP[i][j] = input - 48;
}
}
visited[0][0] = 1;
bfs(0, 0, N-1, M-1);
cout << visited[N - 1][M - 1] << endl;
return 0;
}
📌 memo 😊
ref)