본 게시글은 유튜버 [ 동빈나 ] 님의 유튜브 영상과 git hub 교재 를 공부하고 정리한 글 입니다.
< DFS / BFS >
[#1 음료수 얼려 먹기] / [#2 미로 탈출]
--------------------------------------------------------------------------------------------------------------------------------------------
#1 음료수 얼려 먹기


[ 내 풀이 ]
#include<iostream> #include<vector> using std::cout; using std::cin; using std::vector; vector<vector<int>> adjacent; vector<vector<bool>> visited; // 동서남북 순으로 int dx[] = { 0,-1,0,1 }; int dy[] = { -1,0,1,0 }; int n, m; int result; void dfs(int x,int y) { visited[x][y] = true; for (int i = 0; i < 4; i++) { int newx = x + dx[i]; int newy = y + dy[i]; if (newx >= 0 && newy >= 0 && newx < n && newy < m) { if (!visited[newx][newy] && adjacent[newx][newy]==0) { dfs(newx, newy); } } } } int main() { std::ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cin >> n >> m; adjacent.resize(n); visited.resize(n); adjacent.reserve(1001); visited.reserve(1001); for (int i = 0; i < n; i++) { adjacent[i].resize(m); visited[i].resize(m); adjacent[i].reserve(1001); visited[i].reserve(1001); for (int j = 0; j < m; j++) { scanf_s("%1d", &adjacent[i][j]); } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (adjacent[i][j] == 0 && !visited[i][j]) { dfs(i, j); result++; } } } cout << result; return 0; }
[ 정답 코드 보기 ]
#include <bits/stdc++.h> using namespace std; int n, m; int graph[1000][1000]; // DFS로 특정 노드를 방문하고 연결된 모든 노드들도 방문 bool dfs(int x, int y) { // 주어진 범위를 벗어나는 경우에는 즉시 종료 if (x <= -1 || x >=n || y <= -1 || y >= m) { return false; } // 현재 노드를 아직 방문하지 않았다면 if (graph[x][y] == 0) { // 해당 노드 방문 처리 graph[x][y] = 1; // 상, 하, 좌, 우의 위치들도 모두 재귀적으로 호출 dfs(x - 1, y); dfs(x, y - 1); dfs(x + 1, y); dfs(x, y + 1); return true; } return false; } int main() { // N, M을 공백을 기준으로 구분하여 입력 받기 cin >> n >> m; // 2차원 리스트의 맵 정보 입력 받기 for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { scanf("%1d", &graph[i][j]); } } // 모든 노드(위치)에 대하여 음료수 채우기 int result = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { // 현재 위치에서 DFS 수행 if (dfs(i, j)) { result += 1; } } } cout << result << '\n'; // 정답 출력 }
입력 받는거 부터 막혔던 문제..
내가 아는 DFS/BFS 문제는 전부 인접행렬이나 인접리스트 형태로 풀면 됐었는데 이런류의 문제는 1번? (프로그래머스 고득점kit? ) 정도 접해본거같다.
아직 낯설다.
[ 배운 점 ]
- 공백 없는 숫자를 하나씩 입력 받을때는 scanf("%1d" ,& 주소값) 으로 받아준다.
scanf("%1d", &adjacent[i][j]);
[ 주의할 점 ]
ios::sync_with_stdio(false);
이 코드는 C 와 C++ 의 표준 stream의 동기화를 끊는 역할을 한다.
cin과 cout의 속도가 C의 입출력 속도에 비해 떨어지기 때문에 저 코드를 사용해 속도를 높이는 기능으로 사용한다.
하지만 동기화를 끊게되면 C의 입출력 함수를 더 이상 사용하지 못하게 된다. 때문에 printf와 scanf 같은 함수는 사용하면 안된다.
getchar도 C에서 쓰이는 입출력 함수로 사용 불가.
비쥬얼스튜디오에서는 동기화를 끊어도 섞어쓰면 알아서 처리해주는 것 같지만 채점프로그램에서는 그렇지 않다.
그렇기 때문에 항상 ios::sync_with_stdio(false); 를 쓴다면 C의 입출력을 쓰지 않도록 조심해야한다.
실제로 백준에서 ios::sync_with_stdio(false); 사용하고 scanf 를 사용하면 오류가 뜬다.
cin.tie(NULL); cout.tie(NULL); << 는 버퍼를 조작하는거이기 때문에 scanf 사용과 상관 없다.
#2 미로 탈출


[ 내 풀이 ]
#include<iostream> #include<vector> #include<queue> using std::vector; using std::cin; using std::cout; int graph[201][201]; int visited[201][201]; int n, m; // 동서남북 순으로 int dx[] = { 0,-1,0,1 }; int dy[] = { -1,0,1,0 }; int next_x, next_y; int cur_x, cur_y; void bfs(int x,int y) { std::queue<std::pair<int,int>> que; // que 생성 que.push({ x,y }); visited[x][y]++; // 원하는 위치의 visited 값을 정답으로 사용. while (!que.empty()) { cur_x = que.front().first; cur_y = que.front().second; que.pop(); for (int i = 0; i < 4; i++) { next_x = cur_x + dx[i]; next_y = cur_y + dy[i]; // 그래프가 유효 인덱스에 있고 if (next_x >= 1 && next_x <= n && next_y >= 1 && next_y <= m) { // 방문하지 않고, graph 값이 1이라면 if (!visited[next_x][next_y] && graph[next_x][next_y] == 1) { // que에 push que.push({ next_x,next_y }); // 전 노드 값에서 + 1 ( 시작점과의 거리 표현 ) visited[next_x][next_y] = visited[cur_x][cur_y] + 1; } } if (next_x == n && next_y == m) { cout << visited[next_x][next_y]; return; } } } } int main() { // scanf를 사용하기위해 생략 // std::ios::sync_with_stdio(false); // cin.tie(nullptr); cout.tie(nullptr); cin >> n >> m; // graph 입력받기 for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { scanf_s("%1d", &graph[i][j]); } } bfs(1, 1); // 시작 위치는 항상 1,1 return 0; }
[ 정답 코드 보기 ]
#include <bits/stdc++.h> using namespace std; int n, m; int graph[201][201]; // 이동할 네 가지 방향 정의 (상, 하, 좌, 우) int dx[] = {-1, 1, 0, 0}; int dy[] = {0, 0, -1, 1}; int bfs(int x, int y) { // 큐(Queue) 구현을 위해 queue 라이브러리 사용 queue<pair<int, int> > q; q.push({x, y}); // 큐가 빌 때까지 반복하기 while(!q.empty()) { int x = q.front().first; int y = q.front().second; q.pop(); // 현재 위치에서 4가지 방향으로의 위치 확인 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) continue; // 벽인 경우 무시 if (graph[nx][ny] == 0) continue; // 해당 노드를 처음 방문하는 경우에만 최단 거리 기록 if (graph[nx][ny] == 1) { graph[nx][ny] = graph[x][y] + 1; q.push({nx, ny}); } } } // 가장 오른쪽 아래까지의 최단 거리 반환 return graph[n - 1][m - 1]; } int main(void) { // N, M을 공백을 기준으로 구분하여 입력 받기 cin >> n >> m; // 2차원 리스트의 맵 정보 입력 받기 for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { scanf("%1d", &graph[i][j]); } } // BFS를 수행한 결과 출력 cout << bfs(0, 0) << '\n'; return 0; }
[ 배운 점 ]
- visited 배열을 만들지 않고도 풀수 있구나
'PS > 이코테' 카테고리의 다른 글
[ 이코테 Chapter 4. 구현 ] - 복습 O (0) | 2021.12.24 |
---|---|
[ 이코테 2. Greedy ] (0) | 2021.11.23 |