선언을 전역변수로 하고 main에서 resize를 하니 코드가 깔끔해진 것 같다
#include <iostream>
#include <vector>
#include <queue>
#include <string>
using namespace std;
int n, m;
vector<vector<int>> maze; // 미로 정보를 저장
vector<vector<int>> distan; // 최단 거리
vector<vector<bool>> visited; // 방문 여부
int dx[4] = { 0, 1, 0, -1 }; // 상, 하, 좌, 우
int dy[4] = { 1, 0, -1, 0 };
void bfs() {
queue<pair<int, int>> q;
// 시작점 초기화
q.push({ 0, 0 });
distan[0][0] = 1;
visited[0][0] = true;
while (!q.empty()) {
int x = q.front().first;
int y = q.front().second;
q.pop();
// 상하좌우 탐색
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
// 경계 조건 및 방문 여부 확인
if (nx >= 0 && nx < n && ny >= 0 && ny < m && maze[nx][ny] == 1 && !visited[nx][ny]) {
visited[nx][ny] = true;
distan[nx][ny] = distan[x][y] + 1; // 거리 갱신
q.push({ nx, ny }); // 큐에 추가
}
}
}
}
int main() {
cin >> n >> m;
maze.resize(n, vector<int>(m));
distan.resize(n, vector<int>(m, 0));
visited.resize(n, vector<bool>(m, false));
// 미로 입력
for (int i = 0; i < n; i++) {
string row;
cin >> row;
for (int j = 0; j < m; j++) {
maze[i][j] = row[j] - '0'; // 문자열을 정수로 변환
}
}
// BFS 실행
bfs();
// 도착점까지의 최단 거리 출력
cout << distan[n - 1][m - 1] << endl;
return 0;
}
'개발공부 > 알고리즘 이론' 카테고리의 다른 글
MST 알고리즘(크루스칼, 프림) (0) | 2024.12.07 |
---|---|
Graph-다익스트라 알고리즘(Dijkstra Algorithm) (0) | 2024.12.07 |
그래프란?(Computer Science) bfs, dfs, scc, dag (1) | 2024.12.06 |
시간복잡도 (0) | 2024.10.20 |
알고리즘 시간 복잡도, 마스터 정리 (0) | 2024.10.07 |