1260번: DFS와 BFS
첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사
www.acmicpc.net
dfs(비재귀) - 스택사용
bfs - 큐사용
#include <iostream>
#include <stack>
#include <queue>
using namespace std;
int array[1010][1010] = {0,};
int ch[1010] = {0,};
int ch2[1010] = {0,};
int main()
{
int n, m, s;
int i;
int x, y;
cin >> n >> m >> s;
for(i=0;i<m;i++)
{
cin >> x >> y;
array[x][y] = 1;
array[y][x] = 1;
}
//dfs 스택사용
stack<int> st;
st.push(s);
ch[s] = 1;
cout << s<< ' ';
while(!st.empty())
{
x = st.top();
for(i=1;i<=n;i++)
{
if(ch[i] == 0 && array[x][i] == 1)
{
st.push(i);
cout << i << ' ';
ch[i] = 1;
break;
}
}
if(i > n)
st.pop();
}
cout << '\n';
// bfs 큐사용
queue<int> qu;
qu.push(s);
ch2[s] = 1;
while(!qu.empty())
{
x = qu.front();
cout << x << ' ';
qu.pop();
for(i=1;i<=n;i++)
{
if(ch2[i] == 0 && array[x][i] == 1)
{
qu.push(i);
ch2[i] = 1;
}
}
}
return 0;
}
'백준 문제풀이' 카테고리의 다른 글
D01 Test - Phone Line (0) | 2024.07.31 |
---|---|
백준 10828 - 스택이란? (0) | 2023.09.07 |
백준 1182번 부분수열의 합 소스 코드 - 비트마스크 (0) | 2022.01.06 |
백준 2531번 회전초밥 소스 코드 (0) | 2022.01.06 |
백준 2805번 - 나무 자르기 (0) | 2021.12.17 |