728x90
반응형
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring> // memset 헤더
#include <queue>
using namespace std;
// [백준 2178 c++ VOV] 미로 탐색
// 문제: 미로가 주어졌을 때, (1, 1)에서 출발하여 (N, M)의 위치로 이동할 때 지나야 하는 최소의 칸 수
// 접근: 이차원 그래프 최단거리 -> bfs
// 이동거리를 저장하는 dist배열 따로 저장
// 시간복잡도:
// 풀이 :
// 그래프 입력
// bfs 시작
// 탐색하며 dist에 이동거리 저장
// 주의:
//: ios::sync_with_stdio(false); 사용시 cin,scanf 같이 쓰면 오류
#define MAX 101
int n, m;
int gr[MAX][MAX];
bool visit[MAX][MAX];
int dist[MAX][MAX];
int dx[4] = { 0,0,1,-1 };
int dy[4] = { 1,-1,0,0 };
void bfs(int r, int c) {
queue<pair<int,int>> q;
q.push({ r,c }); visit[r][c] = 1; // 방문처리
dist[r][c] = 1; // 거리 저장
while (!q.empty()) {
r = q.front().first;
c = q.front().second;
q.pop();
// 4방향 탐색
for (int i = 0; i < 4; i++) {
int nr = r + dy[i];
int nc = c + dx[i];
if (nr<1 || nr >n || nc<1 || nc>m) { continue; } // 범위검사
if (!visit[nr][nc] && gr[nr][nc] == 1) { // 방문, 이동유무 검사
q.push({ nr,nc }); visit[nr][nc] = 1; // 큐 푸쉬 방문처리
dist[nr][nc] = dist[r][c] + 1; // 거리저장
}
}
}
}
int main() {
ios::sync_with_stdio(false); // 계산시간 단축 // cin,scanf 같이 쓰면 오류
//cin.tie(nullptr); cout.tie(nullptr);// 입출력 시간 단축 // 이것을 쓰면 scanf,printf섞어 쓰면 안됨
// 2차원 그래프 입력
scanf("%d %d", &n, &m);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
scanf("%1d", &gr[i][j]);
}
}
bfs(1, 1);
printf("%d\n", dist[n][m]);
return 0;
}
|
cs |
반응형
'Algorithm_BOJ(백준) > 깊이,너비우선탐색(DFS,BFS)' 카테고리의 다른 글
[백준 1697 c++ VVO] 숨바꼭질 (0) | 2021.09.02 |
---|---|
[백준 7576 c++ VOO] 토마토 (0) | 2021.09.01 |
[백준 2667 c++ VOOO] 단지번호붙이기 (0) | 2021.08.31 |
[백준 1707 c++ VV] 이분 그래프 (0) | 2021.08.31 |
[백준 11724 c++ OO] 연결 요소의 개수 (0) | 2021.08.31 |