[C++] 1260: DFS와 BFS

쩡우·2023년 1월 8일
0

BOJ algorithm

목록 보기
20/65

문제

그래프를 DFS로 탐색한 결과와 BFS로 탐색한 결과를 출력하는 프로그램을 작성하시오. 단, 방문할 수 있는 정점이 여러 개인 경우에는 정점 번호가 작은 것을 먼저 방문하고, 더 이상 방문할 수 있는 점이 없는 경우 종료한다. 정점 번호는 1번부터 N번까지이다.

입력

첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사이에 여러 개의 간선이 있을 수 있다. 입력으로 주어지는 간선은 양방향이다.

출력

첫째 줄에 DFS를 수행한 결과를, 그 다음 줄에는 BFS를 수행한 결과를 출력한다. V부터 방문된 점을 순서대로 출력하면 된다.

예제 입력 1

4 5 1
1 2
1 3
1 4
2 4
3 4

예제 출력 1

1 2 4 3
1 2 3 4

풀이

DFS, BFS 복습 겸 풀어보았다.
그래프는 2차원 배열로 표현하였다.

코드

#include <iostream>
#include <queue>

using namespace std;

void input_data(void);
void dfs(int now_node);
void bfs(void);

int graph[1001][1001];
int is_visited[1001];
int n, m, v;
queue<int> bfs_queue;

int main(void)
{
	input_data();
	dfs(v);
	cout << '\n';
	fill_n(is_visited, 1001, 0);
	bfs();

	return (0);
}

void input_data(void)
{
	cin >> n >> m >> v;

	int i = 0;
	while (++i <= m)
	{
		int a, b;
		cin >> a >> b;
		graph[a][b] = 1;
		graph[b][a] = 1;
	}

	return ;
}

void dfs(int now_node)
{
	is_visited[now_node] = 1;
	cout << now_node << ' ';

	int i = 0;	
	while (++i <= n)
		if (graph[now_node][i] && !is_visited[i])
			dfs(i);

	return ;
}

void bfs(void)
{
	bfs_queue.push(v);
	is_visited[v] = 1;
	
	while (!bfs_queue.empty())
	{
		int now_node = bfs_queue.front();
		bfs_queue.pop();
		cout << now_node << ' ';
		
		int i = 0;
		while (++i <= n)
		{
			if (graph[now_node][i] && !is_visited[i])
			{
				is_visited[i] = 1;
				bfs_queue.push(i);
			}
		}
	}

	return ;
}
}

성공 !

profile
Jeongwoo's develop story

0개의 댓글