본문 바로가기

algorithm

백준 2178번 미로 탐색

https://www.acmicpc.net/problem/2178

 

아이디어:

1. 입력받을 때, string tmp로 입력받고 이중 for문으로 for(auto x : tmp) board[i][j] = x - '0'; 로 board 배열 입력

2. BFS의 방문을 검사하는 배열인 vis[101][101]에 방문 여부인 bool형이 아닌 해당 위치까지의 거리 int형을 기록

vis[nx][ny] = vis[cur.first][cur.second] + 1;

 

#include <iostream>
#include <bits/stdc++.h>

using namespace std;

int board[101][101];
int vis[101][101];
int dx[4] = { 1, 0, -1, 0 };
int dy[4] = { 0, 1, 0, -1 };

int main() {

	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);

	int n, m;
	string tmp;
	cin >> n >> m;
	queue<pair<int, int>> Q;
	for (int i = 0; i < n; i++) {
		cin >> tmp;
		int j = 0;
		for (auto x : tmp) {
			board[i][j] = x - '0';
			j++;
		}
	}

	vis[0][0] = 1;
	Q.push({ 0, 0 });

	while (!Q.empty()) {
		pair<int, int> cur = Q.front();
		Q.pop();

		for (int dir = 0; dir < 4; dir++) {
			int nx = cur.first + dx[dir];
			int ny = cur.second + dy[dir];
			if (nx < 0 || nx >= n || ny < 0 || ny >= m) continue;
			if (vis[nx][ny] > 0 || board[nx][ny] != 1) continue;
			vis[nx][ny] = vis[cur.first][cur.second] + 1;
			Q.push({ nx, ny });
		}
	}

	cout << vis[n - 1][m - 1];

	return 0;

}

'algorithm' 카테고리의 다른 글

백준 4179번 불!  (0) 2025.04.11
백준 7576번 토마토  (0) 2025.04.06
백준 1926번 그림  (0) 2025.04.05
넓이우선탐색 BFS  (0) 2025.04.05
백준 3986번 좋은 단어  (0) 2025.04.03