본문 바로가기

Programming/BOJ

[백준/C++] 1260번: DFS와 BFS

#include<iostream>
#include<queue>

using namespace std;
int N, M, V;
int map[1001][1001];
int c[1001];

void dfs(int node) {

	cout << node << " ";

	for (int i = 1; i <= N; i++) {
		if (map[node][i] == 1 && c[i] != 1) {
			c[i] = 1;
			dfs(i);
		}
	}

}

int main() {

	cin >> N >> M >> V;
	int x=0;
	int y=0;
	for (int i = 0; i < M; i++) {
		cin >> x >> y;
		map[x][y] = map[y][x] = 1;
	}

	//dfs
	c[V] = 1;
	dfs(V);


	cout << endl;

	//bfs
	queue<int> q;
	int v;
	q.push(V);
	c[V] = 2;

	while (!q.empty()) {
		v = q.front();
		q.pop();
		cout << v << " ";
		for (int i = 1; i <= N; i++) {
			if (map[v][i] == 1 && c[i] != 2) {
				c[i] = 2;
				q.push(i);
			}

		}

	}

	return 0;
}