# 생각

dfs와 bfs 탐색 시 탐색되는 다음 index 값만 출력해주면 쉽게 해결가능하다

dfs와 bfs 탐색의 차이를 보여주는 기초적인 문제다

 

 

# 전체 코드

#include <bits/stdc++.h>
using namespace std;

int n, m, v;
int graph[1111][1111], vis[1111];

void dfs(int index)
{
	cout << index << ' ';
	vis[index] = true;
	for (int nxt = 1; nxt <= n; nxt++)
	{
		if (graph[index][nxt] == 1 and vis[nxt] == false)
		{
			dfs(nxt);
		}
	}
}

void bfs(int st)
{
	queue<int> q;
	q.push(st);
	vis[st] = true;
	while (!q.empty())
	{
		auto cur = q.front();
		q.pop();
		for (int nxt = 1; nxt <= n; nxt++)
		{
			if (graph[cur][nxt] == 1 and vis[nxt] == false)
			{
				q.push(nxt);
				vis[nxt] = true;				
			}
		}
		cout << cur << ' ';
	}
}

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(nullptr);

	cin >> n >> m >> v;
	for (int i = 0; i < m; i++)
	{
		int from, to;
		cin >> from >> to;
		graph[from][to] = 1;
		graph[to][from] = 1;
	}
	dfs(v);
	cout << '\n';
	fill(vis, vis + n + 1, 0);
	bfs(v);
}

 


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

 

1260번: DFS와 BFS

첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사

www.acmicpc.net

+ Recent posts