C++)
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#define MAX_NUM 101
using namespace std;
bool visited[MAX_NUM];
int main(void) {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n, m, x, y;
cin >> n;
cin >> m;
vector<vector<int>> v(n+1);
for (int i = 0; i < m; i++) {
cin >> x >> y;
v[x].push_back(y);
v[y].push_back(x);
}
queue<int> q;
visited[1] = true;
q.push(1);
int ans = 0;
while (!q.empty()) {
int cur = q.front();
q.pop();
for (int i = 0; i < v[cur].size(); i++) {
int next = v[cur][i];
if (!visited[next]) {
visited[next] = true;
q.push(next);
ans++;
}
}
}
cout << ans;
return 0;
}
Python)
import sys
from collections import deque
read = sys.stdin.readline
n = int(read().rstrip())
m = int(read().rstrip())
arr = [ [] for _ in range(n+1)]
visited = [False] * (n+1)
for _ in range(m):
x, y = map(int, read().rstrip().split())
arr[x].append(y)
arr[y].append(x)
q = deque()
visited[1] = True
q.append(1)
ans = 0
while q:
cur = q.popleft()
for next in arr[cur]:
if not visited[next]:
visited[next] = True
q.append(next)
ans += 1
print(ans)'백준 2 > 그래프' 카테고리의 다른 글
| [백준 2583] 영역 구하기 (C++/Python) (0) | 2020.12.08 |
|---|---|
| [백준 1697] 숨바꼭질 (C++/Python) (0) | 2020.12.08 |
| [백준 1012] 유기농 배추 (C++/Python) (0) | 2020.12.08 |
| [백준 9328] 열쇠 (0) | 2020.12.08 |
| [백준 11403] 경로 찾기 (0) | 2020.12.08 |