개인공부용123 프로그래밍 블로그

[백준] 1260 본문

알고리즘문제

[백준] 1260

개인공부용123 2017. 5. 4. 15:09

기본적인 DFS BFS 구현입니다.



#include <iostream>
#include <queue>
#include <string.h>

using namespace std;

bool arr[1001][1001]; // 2차원 배열
bool check_arr[1001];
int N, M, V; // 정점 간선 시작점

void BFS(int start) { // BFS호출순서
	queue q;

	q.push(start);
	check_arr[start] = true;
	cout << start << " ";

	while (!q.empty()) {
		for (int i = 1; i <= N; ++i) {
			if (arr[q.front()][i] == true && check_arr[i] == false) {
				cout << i << " ";
				check_arr[i] = true;
				q.push(i);
			}
		}

		q.pop();
	}
}

void DFS(int start) { // DFS호출순서
	cout << start << " ";
	check_arr[start] = true; // true로 체크

	for (int i = 1; i <= N; ++i) {
		if (arr[start][i] == true && check_arr[i] == false) {
			DFS(i);
		}
	}
	
	return;
}

int main() {
	freopen("test.txt", "r", stdin);
	std::ios::sync_with_stdio(false);
	
	memset(arr, false, sizeof(arr));
	memset(check_arr, false, sizeof(check_arr));
	
	cin >> N >> M >> V;
	int v1, v2;
	for (int i = 0; i < M; ++i) {
		cin >> v1 >> v2;
		arr[v1][v2] = true;
		arr[v2][v1] = true;
	}

	DFS(V);
	cout << endl;
	memset(check_arr, false, sizeof(check_arr));
	BFS(V);
	cout << endl;

	return 0;
}


'알고리즘문제' 카테고리의 다른 글

[백준] 5430  (0) 2017.05.04
[백준] 11866 & 1158 (조세퍼스문제 0, 1)  (0) 2017.05.04
[백준] 9012  (0) 2017.05.02
[백준] 1874(스택)  (0) 2017.05.02
[백준] 1929 (에라토스테네스의 체)  (0) 2017.05.02