[Algorithm] DFS & BFS

2020. 3. 16. 17:15Problem solving/Algorithm

https://www.acmicpc.net/problem/1260

불러오는 중입니다...
#include <iostream>
#include <queue>
#include <stack>

using namespace std;

int graph[1001][1001];
bool visited[1001];
int n, m, v;
void dfs(int start) {
	memset(visited, false, sizeof(visited));
	stack<int> s;
	s.push(start);
	while (!s.empty()) {
		int current_node = s.top();
		s.pop();
		if (!visited[current_node]) {
			visited[current_node] = true;
			cout << current_node << " ";
			for (int i = n; i > 0; i--)
				if (!visited[i] && graph[current_node][i] == 1) s.push(i);
		}
	}
	cout << "\n";
}
void bfs(int start) {
	memset(visited, false, sizeof(visited));
	queue<int> q;
	q.push(start);
	while (!q.empty()) {
		int current_node = q.front();
		q.pop();
		if (!visited[current_node]) {
			visited[current_node] = true;
			cout << current_node << " ";
			for (int i = 1; i <= n; i++)
				if (!visited[i] && graph[current_node][i] == 1) q.push(i);
		}
	}

}
int main() {
	ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
	cin >> n >> m >> v;
	for (int i = 0; i < m; i++) {
		int s, e;
		cin >> s >> e;
		graph[s][e] = 1;
		graph[e][s] = 1;
	}
	dfs(v);
	bfs(v);
	return 0;
}