[BOJ] 1260. DFS와 BFS

동스토리 ㅣ 2020. 9. 23. 21:28

반응형

문제

www.acmicpc.net/problem/1260

 

1260번: DFS와 BFS

첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사

www.acmicpc.net


풀이

DFS & BFS

ehdtn1219.tistory.com/46?category=810792

 

DFS & BFS

DFS(Depth First Search): 깊이 우선 탐색 BFS(Breadth Firsh Search): 너비 우선 탐색

ehdtn1219.tistory.com


코드

#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
const int MAX = 1001;
int N, M, V; // N: 정점의 개수, M: 간선의 개수, V: 시작할 정점의 번호
int map[MAX][MAX];
int visit[MAX];

void dfs(int V) {

	cout << V << ' ';
	visit[V] = 1;
	for (int i = 1; i <= N; i++) {
		if (map[V][i]==0 || visit[i] == 1 )continue;
		dfs(i);
	}
}

void bfs(int V) {

	queue<int> q;
	q.push(V);
	visit[V] = 0;
	while (!q.empty()) {
		V = q.front();
		cout << V << ' ';
		q.pop();
		for (int i = 1; i <= N; i++) {
			if (map[V][i] == 0 || visit[i] == 0)continue;
			q.push(i);
			visit[i] = 0;
		}
	}
}

int main() {

	cin >> N >> M >> V;
	int x, y;
	for (int i = 0; i < M; i++) {
		cin >> x >> y;
		map[x][y] = map[y][x] = 1;
	}
	dfs(V);
	cout << '\n';
	bfs(V);
	return 0;
}

 

반응형

'Development > Algorithm' 카테고리의 다른 글

[BOJ] 2751. 수 정렬하기2  (0) 2020.09.24
[프로그래머스] 완주하지 못한 선수  (0) 2020.09.23
[SWEA] 1859. 백만 장자 프로젝트  (0) 2020.09.23
[BOJ] 11057. 오르막수  (0) 2020.09.22
[BOJ] 10844. 쉬운 계단 수  (0) 2020.09.20