상세 컨텐츠

본문 제목

백준 1260번 //DFS와 BFS//

cote/Intermediate

by geminanolja 2025. 1. 20. 20:39

본문

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

 

#include<iostream>
#include<vector>
#include<algorithm>
#include<queue>
using namespace std;

void DFS(int startNode, vector<vector<int>>& graph, vector<bool>& visited)
{
	visited[startNode] = true; //start노드 방문처리
	cout << startNode << " "; // 출력!
	for (auto neighbor : graph[startNode])//startNode와 연결된 이웃노드 방문시도
	{
		if (!visited[neighbor])//방문 안했으면
		{
			DFS(neighbor, graph, visited);
		}
	}

}

void BFS(int startNode, vector<vector<int>>& graph)
{
	vector<bool> visited(graph.size(), false);// 방문 여부를 저장하는 배열
	queue<int> q;// BFS를 위한 큐 생성***중요***
	q.push(startNode);
	visited[startNode] = true;

	while (!q.empty())
	{
		int node = q.front();
		q.pop();
		cout << node << " ";
		for (int neighbor : graph[node])
		{
			if (!visited[neighbor])
			{
				q.push(neighbor);
				visited[neighbor] = true;
			}
		}
	}
}

int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);

	int n, m, v;
	cin >> n >> m >> v;
	vector<vector<int>> edges(n+1);
	for (int i = 0; i < m; i++)
	{
		int a, b;
		cin >> a >> b;
		edges[a].push_back(b);
		//cout << "a : " << a << " b : " << b << endl;
		edges[b].push_back(a);
	}

	for (int i = 0; i <= n; i++)//작은번호부터 방문
	{
		sort(edges[i].begin(), edges[i].end());
	}

	vector<bool> visited(n+1, false);
	DFS(v, edges, visited);
	cout << endl;

	BFS(v, edges);
	cout << endl;


	return 0;
}

 

관련글 더보기