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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | #include <stdio.h> #include <queue> using namespace std; int adj[1005][1005] = { 0 }; int chk1[1005] = { 0 }; int chk2[1005] = { 0 }; int n, m, v; void DFS(int v); void BFS(int v); int main() { scanf("%d %d %d", &n, &m, &v); for (int i = 1; i <= m; i++) { int a, b; scanf("%d %d", &a, &b); adj[a][b] = 1; adj[b][a] = 1; } chk1[v] = 1; DFS(v); printf("\n"); chk2[v] = 1; BFS(v); } void DFS(int v) { printf("%d ", v); for (int i = 1; i <= n; i++) { if (adj[v][i] == 1 && chk1[i]==0) { chk1[i] = 1; DFS(i); } } } void BFS(int v) { printf("%d ", v); queue<int> q; q.push(v); while (q.empty() == false) { int node = q.front(); q.pop(); for (int i = 1; i <= n; i++) { if (adj[node][i] == 1 && chk2[i] == 0) { chk2[i] = 1; q.push(i); printf("%d ", i); } } } } | cs |
'알고리즘 > DFS' 카테고리의 다른 글
1012 유기농 배추 (0) | 2019.07.29 |
---|---|
2667 단지번호 붙이기 (0) | 2019.07.29 |
(잘못된풀이) 누가 더 클까 더블릿 (0) | 2019.03.01 |
달팽이 더블릿 (0) | 2019.02.28 |
(복습 필요) orders 더블릿 (0) | 2019.02.26 |