728x90
BFS ๋ก ๊ฐ๋จํ๊ฒ ์ฌ์ดํด์ visitedํ๊ฒ ๋๋ node๊ฐ ๋ช ๊ฐ์ธ์ง ์ธ์ด์ฃผ๋ฉด ๋๋ค.
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int main() {
int computer = 0;
int num = 0;
cin >> computer;
cin >> num;
vector<vector<int>> adj(computer+1);
vector<int> visited(computer, 0);
queue<int> q;
for(int i = 0 ; i < num ; i++) {
int one = 0, two = 0;
cin >> one >> two;
adj[one].push_back(two);
adj[two].push_back(one);
}
// for(int i =1 ; i < adj.size() ; i++) {
// cout << "[ " << i << " ] ";
// for(int j =0 ; j < adj[i].size() ; j++) {
// cout << adj[i][j] << " ";
// }
// cout << endl;
// }
int connected = 0;
q.push(1);
visited[1] = 1;
while(!q.empty()) {
int node = q.front();
q.pop();
for(int i = 0 ; i < adj[node].size() ; i++) {
if(visited[adj[node][i]] == 0) {
connected++;
visited[adj[node][i]] = 1;
q.push(adj[node][i]);
}
}
}
cout << connected ;
return 0;
}
'๐ Self Study > ๐ BaekJoon' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๋ฐฑ์ค BaekJoon (์คํํธ๋งํฌ, 5014๋ฒ) C++ (0) | 2022.01.11 |
---|---|
๋ฐฑ์ค BaekJoon (์จ๋ฐ๊ผญ์ง, 1697๋ฒ) C++ (0) | 2022.01.11 |
๋ฐฑ์ค BaekJoon (ํ ๋งํ , 7569๋ฒ) C++ (0) | 2022.01.11 |
๋ฐฑ์ค BaekJoon(์ด์ ๊ณ์ฐ, 2644๋ฒ) C++ (0) | 2022.01.10 |
๋ฐฑ์ค BaekJoon (DFS์ BFS, 1260) C++ (0) | 2022.01.05 |