알고리즘/백준
백준1260_DFS와 BFS
래울
2020. 6. 3. 20:11
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 <stdio.h>
#define MAX 1001
int graph[MAX][MAX]={0,};
int bfs[MAX]={0,};
int dfs[MAX]={0,};
void DFS(int N, int s);
void BFS(int N, int s);
int main(){
int N,M,V;
scanf("%d %d %d",&N,&M,&V);
int n;
int i,a,b;
for(i=0; i<M; i++){
scanf("%d",&a);
scanf("%d",&b);
graph[a][b]=1;
graph[b][a]=1;
}
DFS(N,V);
putchar('\n');
BFS(N,V);
return 0;
}
void DFS(int N, int s){
int i;
printf("%d ",s);
dfs[s]=1;
for(i=1; i<=N; i++){
if(graph[s][i]==1 && dfs[i]!=1)
DFS(N,i);
}
}
void BFS(int N, int s){
int i;
int front = -1;
int rear = -1;
int queue[10001]={0,};
int pop;
rear++;
queue[rear] = s;
bfs[s]=1;
printf("%d ", s);
while (front < rear) {
front++;
pop = queue[front];
for (i=1; i <= N; i++) {
if (graph[pop][i] == 1 && bfs[i] == 0) {
rear++;
queue[rear] = i;
bfs[i] = 1;
printf("%d ", i);
}
}
}
}