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;
}
백준 2667 //단지번호붙이기 (0) | 2025.01.22 |
---|---|
백준 1697//숨바꼭질 (0) | 2025.01.21 |
백준 // 2470//두 용액/ 항해99//정렬과 투 포인터(Two Pointers) 알고리즘 (0) | 2025.01.19 |
백준 //선분 위의 점//11663//정렬(Sorting)**과 **이분 탐색(Binary Search) (0) | 2025.01.19 |
항해99 백준 2343번 // 블루레이 강의 (0) | 2025.01.17 |