바이러스
신종 바이러스인 웜 바이러스는 네트워크를 통해 전파된다. 한 컴퓨터가 웜 바이러스에 걸리면
그 컴퓨터와 네트워크 상에서 연결되어 있는 모든 컴퓨터는 웜 바이러스에 걸리게 된다.
예를 들어 7대의 컴퓨터가 <그림 1>과 같이 네트워크 상에서 연결되어 있다고 하자.
1번 컴퓨터가 웜 바이러스에 걸리면 웜 바이러스는 2번과 5번 컴퓨터를 거쳐 3번과 6번 컴퓨터까지 전파되어 2, 3, 5, 6 네 대의 컴퓨터는 웜 바이러스에 걸리게 된다.
하지만 4번과 7번 컴퓨터는 1번 컴퓨터와 네트워크상에서 연결되어 있지 않기 때문에 영향을 받지 않는다.

어느 날 1번 컴퓨터가 웜 바이러스에 걸렸다. 컴퓨터의 수와 네트워크 상에서 서로 연결되어 있는 정보가 주어질 때, 1번 컴퓨터를 통해 웜 바이러스에 걸리게 되는 컴퓨터의 수를 출력하는 프로그램을 작성하시오.
입력
첫째 줄에는 컴퓨터의 수가 주어진다. 컴퓨터의 수는 100 이하이고 각 컴퓨터에는 1번 부터 차례대로 번호가 매겨진다.
둘째 줄에는 네트워크 상에서 직접 연결되어 있는 컴퓨터 쌍의 수가 주어진다. 이어서 그 수만큼 한 줄에 한 쌍씩 네트워크 상에서 직접 연결되어 있는 컴퓨터의 번호 쌍이 주어진다.
출력
1번 컴퓨터가 웜 바이러스에 걸렸을 때, 1번 컴퓨터를 통해 웜 바이러스에 걸리게 되는 컴퓨터의 수를 첫째 줄에 출력한다.
예제 입력
7 6 1 2 2 3 1 5 5 2 5 6 4 7
예제 출력
4문제를 틀렸던 이유.
→ 제대로 문제를 보지 않았다.
오답코드 ——-
#include<iostream> #include <vector> #include <queue> #include <list> using namespace std; bool visited[101]; vector<int> adjancent[101]; void DFS(int here) { if (visited[here] == true) return; for (int i = 0; i < adjancent[here].size(); i++) { cout << adjancent[here][i] << '\n'; } } int main() { ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int computerQuantity; int computerAdajancent; cin >> computerQuantity >> computerAdajancent; for (int i = 0; i < computerAdajancent; i++) { int a, b; cin >> a >> b; adjancent[a].push_back(b); adjancent[b].push_back(a); } DFS(computerQuantity); }
정답코드 ——
#include<iostream> #include <vector> #include <queue> #include <list> using namespace std; bool visited[101]; vector<int> adjancent[101]; int cnt = 0; void DFS(int here) { if (visited[here] == true) return; visited[here] = true; cnt++; for (int i = 0; i < adjancent[here].size(); i++) { DFS(adjancent[here][i]); } } int main() { ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int computerQuantity; int computerAdajancent; cin >> computerQuantity >> computerAdajancent; for (int i = 0; i < computerAdajancent; i++) { int a, b; cin >> a >> b; adjancent[a].push_back(b); adjancent[b].push_back(a); } DFS(1); cnt--; cout << cnt << endl; }
1번 컴퓨터에 감염된 숫자를 구해야 했었는데.
입력값 7번에 감염된 컴퓨터를 출력하는 문제로 착각했었다.
풀이 난이도 2번 정도 해보면 익혀질 것 같음