미로에서 1은 이동할 수 있는 칸을 나타내고, 0은 이동할 수 없는 칸을 나타낸다. 이러한 미로가 주어졌을 때, (1, 1)에서 출발하여 (N, M)의 위치로 이동할 때 지나야 하는 최소의 칸 수를 구하는 프로그램을 작성하시오. 한 칸에서 다른 칸으로 이동할 때, 서로 인접한 칸으로만 이동할 수 있다. 위의 예에서는 15칸을 지나야 (N, M)의 위치로 이동할 수 있다. 칸을 셀 때에는 시작 위치와 도착 위치도 포함한다.
입력
4 6 101111 101010 101011 111011
출력
15
코드
#include<iostream>
#include<queue>
using namespace std;
string board[101];
int row, col;
int visited[101][101];
queue<pair<int, int>>que;
int dx[] = { 1, 0, -1, 0 };
int dy[] = { 0, 1, 0, -1 };
void BFS(int x, int y)
{
que.push({ x, y });
visited[x][y] = 1;
while (!que.empty())
{
int x = que.front().first;
int y = que.front().second;
que.pop();
for (int i = 0; i < 4; i++)
{
int nx = x + dx[i];
int ny = y + dy[i]; // row 행사이즈, col 열사이즈
if (nx < 0 || nx >= row || ny < 0 || ny >= col ) continue;
if (board[nx][ny] == '1' && visited[nx][ny] == 0)
{
que.push({ nx, ny });
visited[nx][ny] = visited[x][y] + 1;
}
}
}
}
int main()
{
cin >> row >> col; // 행사이즈 // 열사이즈
for (int i = 0; i < row; i++)
{
cin >> board[i];
}
BFS(0, 0);
cout << visited[row - 1][col - 1];
}