-
[BFS]-연습-미로 탐색알고리즘 스터디 01/숙제 2022. 11. 25. 01:02
< BFS > - < 실버 1 >
링크
[ 2178 ] 미로 탐색
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개의 정수로 미로가 주어진다. 각각의 수들은 붙어서 입력으로 주어진다.
:: 출력 ::
첫째 줄에 지나야 하는 최소의 칸 수를 출력한다. 항상 도착위치로 이동할 수 있는 경우만 입력으로 주어진다.
첫번째 연습문제보다 쉽게 풀었다
dis[nx][ny] = dis[cur.first][cur.second]+1;
부분을 생각해내기만 하면 기본 BFS 코드로 충분히 풀 수 있는 문제정답 코드
#include <iostream> #include <utility> // pair 가 들어있는 헤더 #include <queue> using namespace std; int board[101][101]; int visit[101][101]; int dis[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); int n, m; cin >> n >> m; for (int i = 0; i < n; i++) { string s; cin >> s; for (int j = 0; j < s.length(); j++) { board[i][j] = s[j] - '0'; } } /*for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cout << board[i][j]; } cout << "\n"; }*/ queue<pair<int, int>> q; q.push({ 0,0 }); visit[0][0] = 1; dis[0][0] = 1; 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 (visit[nx][ny] == 1 || board[nx][ny] == 0) continue; visit[nx][ny] = 1; dis[nx][ny] = dis[cur.first][cur.second]+1; q.push({ nx,ny }); } } cout << dis[n-1][m-1]; }
1/25
다시 품 한번에 성공함
전에는 배열을 쓸데없이 하나 더 쓴 듯#include <iostream> #include <vector> #include <string> #include <algorithm> #include <queue> using namespace std; int board[101][101]; int dist[101][101]; int dir_x[] = { 0, 1, 0, -1 }; int dir_y[] = { 1, 0, -1, 0 }; int main() { int n, m; cin >> n >> m; for (int i = 0; i < n; i++) { string s; cin >> s; for (int j = 0; j < s.length(); j++) { board[i][j] = s[j] - '0'; } } queue<pair<int, int>> q; q.push(make_pair(0, 0)); dist[0][0] = 1; 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 + dir_x[i]; int ny = y + dir_y[i]; if (nx < 0 || ny < 0 || nx >= n || ny >= m) continue; if (board[nx][ny] == 0 || dist[nx][ny] != 0) continue; dist[nx][ny] = dist[x][y] + 1; q.push(make_pair(nx, ny)); } } cout << dist[n - 1][m - 1]; }
'알고리즘 스터디 01 > 숙제' 카테고리의 다른 글
[BFS]-연습-불! (0) 2022.12.14 [BFS]-연습-토마토 (0) 2022.12.06 [BFS]-연습-그림 (0) 2022.11.25 [스택의 활용]-기본-좋은 단어 (0) 2022.11.21 [스택의 활용]-연습-균형잡힌 세상 (0) 2022.11.21