#include <iostream>
#include <vector>
#include <queue>
#define COMMAX 101
using namespace std;
int netNum, comNum;
vector<int> node[COMMAX];
bool visited[COMMAX];
int counts = 0;
void BFS(int curr);
int main()
{
ios::sync_with_stdio(false);
cin >> comNum;
cin >> netNum;
for (int i = 0; i < netNum; i++)
{
int temp[2];
cin >> temp[0] >> temp[1];
node[temp[0]].push_back(temp[1]);
node[temp[1]].push_back(temp[0]);
}
BFS(1);
cout << counts;
}
void BFS(int curr)
{
queue<int> q;
q.push(curr);
visited[curr] = true;
while (!q.empty())
{
int currNode = q.front();
q.pop();
for (int i = 0; i < node[currNode].size(); i++)
{
int nextNode = node[currNode][i];
if (!visited[nextNode])
{
q.push(nextNode);
visited[nextNode] = true;
counts++;
}
}
}
}
풀이
- DFS나 BFS로 풀면 된다.
- 유의사항은 1은 포함 안 한 나머지 감염된 PC들의 개수를 세면된다.
- 양방향리스트를 사용한다.
- 연결되어 있는 리스트안만 검색하므로 1부터 시작한 리스트만 모두 순회한다.
BFS 설명 : chanheess.tistory.com/45
너비 우선 탐색 BFS
bool BFS(int cost) { queue q; q.push(start); visited[start] = true; while (!q.empty()) { int currNode = q.front(); //현재 너비에 있는 것을 순차적으로 검색 q.pop(); //검색한 곳은 삭제 if (currNode ==..
chanheess.tistory.com
DFS 설명 : chanheess.tistory.com/25
깊이 우선 탐색_DFS
#include #include #include #include using namespace std; const int N = 6; vector number[N]; bool visited[N]{false}; void DFS(int curr); int main() { ios::sync_with_stdio(false); //무방향 리스트 numb..
chanheess.tistory.com
'Algorithm > Baekjoon' 카테고리의 다른 글
[C++] 백준 1325 효율적인 해킹 BFS, DFS (0) | 2021.03.30 |
---|---|
[C++] 백준 1012 유기농 배추 DFS, BFS (0) | 2021.03.29 |
[C++] 백준 1697 숨바꼭질 BFS (0) | 2021.03.26 |
[C++] 백준 1260 DFS와 BFS (0) | 2021.03.25 |
[C++] 백준 2655 가장높은탑쌓기 DP (0) | 2021.03.23 |