250x250
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 |
Tags
- date
- 큐
- priority_queue
- CSS
- map
- 스택
- union_find
- BFS
- 스프링부트
- Properties
- scanner
- GC로그수집
- Java
- sql
- 리소스모니터링
- alter
- JPA
- set
- List
- dfs
- spring boot
- 힙덤프
- string
- javascript
- Union-find
- NIO
- html
- deque
- Calendar
- math
Archives
- Today
- Total
매일 조금씩
프로그래머스 코테 연습 : 네트워크 [C++] DFS/BFS 본문
728x90
반응형
DFS, BFS 두가지 방법으로 풀었다.
DFS와 BFS는 탐색 경로가 다른것 뿐이지 비슷하다.
#include <string>
#include <vector>
#include <queue>
using namespace std;
const int MAX = 200;
int answer = 0;
bool visited[MAX];
void dfs(vector<vector<int>> computers, int node){
visited[node] = true;
// 다른 노드들을 모두 체크
for(int i = 0; i<computers.size(); i++){
// 만약 현재노드와 연결된 노드이고 방문한적 없는 노드이면
if(!visited[i] && computers[node][i]){
// 재귀
dfs(computers, i);
}
}
}
void bfs(vector<vector<int>> computers, int node){
queue<int> q;
q.push(node);
while(!q.empty()){
int front = q.front();
q.pop();
for(int i = 0; i < computers.size(); i++){
if(!visited[i] && computers[front][i]){
q.push(i);
visited[i] = true;
}
}
}
}
int solution(int n, vector<vector<int>> computers) {
for(int i=0; i<n ; i++){
// 방문되지 않은 노드이면 dfs 호출
// dfs문에서 미리 불렸을수 있기 때문에 방문여부 체크 필요
if(!visited[i]){
// dfs
// dfs(computers, i); // 노드와 연결된 노드들을 모두 돌고 나온다.
// bfs
bfs(computers, i);
// 네트워크 수를 ++ 시킨다.
answer++;
}
}
return answer;
}
728x90
반응형
'알고리즘 > Graph (DFS, BFS)' 카테고리의 다른 글
프로그래머스 코테 연습 : DFS/BFS - 여행경로 C++ (0) | 2021.06.10 |
---|---|
프로그래머스 코테 연습 : 단어 변환 [C++] DFS (0) | 2021.04.19 |
프로그래머스 코테 연습 : 타겟 넘버 [C++] DFS (0) | 2021.04.16 |
백준 2583번 : 영역 구하기 [C++] (0) | 2020.08.09 |
백준 2468번 : 안전 영역 [C++] (0) | 2020.08.09 |