본문 바로가기

Algorithm/BAEKJOON

[BOJ] 1260번 DFS와 BFS (C++)

728x90
반응형

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>
#include <stack>
#include <queue>
using namespace std;

int n, v;
int map[1001][1001];
int visit[1001];

void reset() {
	for (int i = 1; i <= n; i++) {
		visit[i] = 0;
	}
}

void dfs() {
	stack<int> s;
	s.push(v);

	while (!s.empty()) {
		int node = s.top();
		s.pop();
		if(!visit[node]) cout << node << " ";
		visit[node] = 1;

		for (int i = n; i > 0; i--) {
			if (!visit[i] && map[node][i] == 1) {
				s.push(i);
			}
		}
	}
	cout << endl;
}

void bfs() {
	visit[v] = 1;
	queue<int> q;
	q.push(v);

	while (!q.empty()) {
		int node = q.front();
		cout << node << " ";
		q.pop();

		for (int i = 1; i <= n; i++) {
			if (!visit[i] && map[node][i] == 1) {
				q.push(i);
				visit[i] = 1;
			}
		}
	}
	cout << endl;
}

int main() {
	int m, n1, n2;
	cin >> n >> m >> v;

	for (int i = 0; i < m; i++) {
		cin >> n1 >> n2;
		map[n1][n2] = map[n2][n1] = 1;
	}

	dfs();
	reset();
	bfs();
	return 0;
}
728x90
반응형