Algorithm/BOJ
백준 1260번 C++
poopooreum
2023. 7. 22. 17:32
반응형
백준 1260번 DFS와 BFS
https://www.acmicpc.net/problem/1260
1260번: DFS와 BFS
첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사
www.acmicpc.net


정답 코드
#include<iostream>
using namespace std;
int arr[1001][1001];
int map[1001];
int used[1001];
int used2[1001];
int n, m, start;
int head = 0, tail = 1;
struct node {
int num, level;
};
node que[1001];
void dfs(int dx);
int main() {
cin >> n >> m >> start;
for (int x = 0; x < m; x++) {
int a, b;
cin >> a >> b;
arr[a][b] = 1;
arr[b][a] = 1;
}
int startindex = 0;
for (int x = 0; x < n; x++)
map[x] = x + 1;
used[start] = 1;
dfs(start);
cout << endl;
que[0] = { start,0 };
used2[start] = 1;
cout << start << " ";
while (head != tail) {
node now = que[head];
for (int x = 0; x <=n; x++) {
if (arr[now.num][x] == 1 && used2[x] == 0) {
cout << x << " ";
que[tail++] = { x,now.level + 1 };
used2[x] = 1;
}
}
head++;
}
}
void dfs(int now) {
cout << now << " ";
for (int x = 0; x <= n; x++) {
if (arr[now][x] == 1&&used[x]==0) {
used[x] = 1;
dfs(x);
}
}
}
BFS와 DFS를 구현하는 기본적인 문제입니다. 제 코드를 보시기보다는 유튜브나 인터넷에서 좀 더 정석적인 코드를 찾고 공부하시는 걸 추천드립니다
반응형