N×M크기의 배열로 표현되는 미로가 있다.
1 0 1 1 1 1
1 0 1 0 1 0
1 0 1 0 1 1
1 1 1 0 1 1
미로에서 1은 이동할 수 있는 칸을 나타내고, 0은 이동할 수 없는 칸을 나타낸다. 이러한 미로가 주어졌을 때, (1, 1)에서 출발하여 (N, M)의 위치로 이동할 때 지나야 하는 최소의 칸 수를 구하는 프로그램을 작성하시오. 한 칸에서 다른 칸으로 이동할 때, 서로 인접한 칸으로만 이동할 수 있다.
위의 예에서는 15칸을 지나야 (N, M)의 위치로 이동할 수 있다. 칸을 셀 때에는 시작 위치와 도착 위치도 포함한다.
첫째 줄에 두 정수 N, M(2 ≤ N, M ≤ 100)이 주어진다. 다음 N개의 줄에는 M개의 정수로 미로가 주어진다. 각각의 수들은 붙어서 입력으로 주어진다.
첫째 줄에 지나야 하는 최소의 칸 수를 출력한다. 항상 도착위치로 이동할 수 있는 경우만 입력으로 주어진다.
처음에 짰던 BFS 코드..
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool visited[101][101]; //전역이라서 자동으로 false로 초기화됨
//상하좌우 이동을 나타내는 배열
int dx[4] = { 1, 0, -1, 0 };
int dy[4] = { 0, 1, 0,- 1 };
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int N, M;
cin >> N >> M;
vector<vector<int>> arr(N+1, vector<int>(M+1));
vector<vector<int>> dp(N+1, vector<int>(M+1, 0));
for(int i=1; i<=N; i++){
string line;
cin >> line; // 공백 없이 한 줄 통째로 받기
for (int j = 1; j <= M; j++)
arr[i][j] = line[j - 1] - '0'; // 문자 -> 정수 변환
}
// <BFS>
// 길이 나져있는 방향으로 BFS로 가면서, (N,M)에 도달하면 멈춰서 해당 step 단계 출력!!
queue<pair<int,int>> q; //(x,y)
q.push({1,1}); // 시작점 push
visited[1][1] = true; // 시작점 방문처리
int count = 0;
while (!q.empty()){
count++; // step 횟수
pair<int,int> cur = q.front();
q.pop();
cout << "(" << cur.first << ", " << cur.second << ") " << endl;
// 현재 위치에서 이동 가능한 모든 지점을 확인 -> 상하좌우 내에 있는 1
//0: 오른쪽, 1: 아래쪽, 2: 왼쪽, 3: 위쪽
for(int i = 0; i < 4; i++){ // 상하좌우 네 칸을 확인하는 for문
int nx = cur.first + dx[i];
int ny = cur.second + dy[i];
if (nx >= 1 && nx <= N && ny >= 1 && ny <= M) { // ✅ 범위 먼저 검사
if (!visited[nx][ny] && arr[nx][ny] == 1) {
if(nx==N && ny==M){
cout << count;
return 0;
}
visited[nx][ny] = true;
q.push({nx, ny});
}
}
}
}
return 0;
}
depth를 기록하지 않아서, 그냥 탐색을 할 때마다 count가 증가되게 됐었다. queue에 여러 depth가 섞여있을 때 거리에 상관없이 count가 올라가버린다.
그래서 이렇게 말고, 몇 회째로 queue에 push 했는지를 나타내는 ‘depth’를 기록해주어야 했다.
→ 좌표 pair에 depth를 추가함!
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
bool visited[101][101];
int dx[4] = { 1, 0, -1, 0 };
int dy[4] = { 0, 1, 0, -1 };
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int N, M;
cin >> N >> M;
vector<vector<int>> arr(N + 1, vector<int>(M + 1));
for (int i = 1; i <= N; i++) {
string line;
cin >> line;
for (int j = 1; j <= M; j++)
arr[i][j] = line[j - 1] - '0';
}
// 큐에 depth (단계)를 같이 저장
queue<pair<pair<int, int>, int>> q;
q.push({{1, 1}, 1}); // (좌표, depth)
visited[1][1] = true;
while (!q.empty()) {
auto cur = q.front();
q.pop();
int x = cur.first.first;
int y = cur.first.second;
int depth = cur.second;
if (x == N && y == M) {
cout << depth << '\n'; // 도착하면 depth 출력
return 0;
}
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx >= 1 && nx <= N && ny >= 1 && ny <= M) {
if (!visited[nx][ny] && arr[nx][ny] == 1) {
visited[nx][ny] = true;
q.push({{nx, ny}, depth + 1});
}
}
}
}
return 0;
}