Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 플레이어 이동
- 백준 10799번 c++
- 배열 stack overflow
- 유니티 Rigidbody 이동
- 2644번
- 프로그래머스 단체사진 찍기 C++
- 백준 2193번 c++
- 유니티
- 백준 2225번 c++
- 백준
- 로블록스 script local script 차이
- UML Diagram 정리
- rigidbody.position
- long int 의 차이
- 차이
- 백준 10844번 c++
- 백준 11726번 C++
- 유니티 꿀팁
- 풀이
- 프로그래머스 가장 큰 수 C++
- rigidbody.Moveposition
- bfs
- 코드
- transform.position
- 유니티 LTS
- c++
- 1699번
- 백준 17299번 c++
- TOPCIT 후기
- TOPCIT 문제 유형
Archives
- Today
- Total
Kiki Devlog
[실 2][C++] 백준 1260번 DFS와 BFS 본문
728x90
문제
풀이
dfs는 재귀를 사용했고 bfs 는 queue를 사용하여 구현했다.
주의할 점은 한 노드에 노드가 여러개 연결돼있다면 작은 번호 순으로 방문한다는 조건을 잊지 않는 것이다.
(이 조건 때문에 첫,두번째 제출이 틀렸음. 그래서 sort 함수를 사용하여 노드를 정렬하고 bfs,dfs를 실행했다.)
코드
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
vector<vector<int>> graph(1001);//각node에 연결된 node들
bool nodeVisit[1001] = {false};
vector<int> answer;
queue<int> q;
void dfs(int curNode) {
nodeVisit[curNode] = true;
answer.push_back(curNode);
for (int i = 0; i < graph[curNode].size(); i++) {
int nextNode = graph[curNode][i];
if (!nodeVisit[nextNode]) {//새로 감염된 컴퓨터라면 카운트.
nodeVisit[nextNode] = true;
dfs(nextNode);
}
}
}
void bfs(int startNode) {
q.push(startNode);
nodeVisit[startNode] = true;
while (!q.empty()) {
int curNode = q.front();
for (int i = 0; i < graph[curNode].size(); i++) {
int nextNode = graph[curNode][i];
if (!nodeVisit[nextNode]) {//새로 감염된 컴퓨터라면 카운트.
nodeVisit[nextNode] = true;
q.push(nextNode);
}
}
answer.push_back(curNode);
q.pop();
}
return;
}
int main() {
int nodeNum, connNum,startNode;
cin >> nodeNum >> connNum>> startNode;
//graph 만들기
int nOne, nTwo;
for (int i = 0; i < connNum; i++) {
cin >> nOne >> nTwo;
graph[nOne].push_back(nTwo);
graph[nTwo].push_back(nOne);
}
//작은 순으로 연결된 node정렬
for (int i = 1; i <= nodeNum; i++) {
sort(graph[i].begin(), graph[i].end());
}
//dfs 시작
dfs(startNode);
//dfs 답 출력
for (int i = 0; i < answer.size(); i++) {
int curNode = answer[i];
cout << curNode << " ";
nodeVisit[curNode] = false;
}
cout << endl;
answer.clear();
//bfs 시작
bfs(startNode);
//bfs 답 출력
for (int i = 0; i < answer.size(); i++) {
int curNode = answer[i];
cout << curNode << " ";
nodeVisit[curNode] = false;
}
return 0;
}
'Coding Test > 백준' 카테고리의 다른 글
[골5][C++] 백준 2225번 합분해 (0) | 2022.10.09 |
---|---|
[실 1][C++] 백준 2178번 미로 탐색 (BFS/DFS 풀이) (0) | 2022.09.07 |
[실 3][C++] 백준 2606번 바이러스 (DFS) (0) | 2022.08.30 |
[실 5][C++] 백준 17478번 재귀함수가 뭔가요? (0) | 2022.08.15 |
[실2][C++] 백준 1699번 제곱수의 합 (dp) (0) | 2022.06.28 |
Comments