C# 백준 알고리즘
C# 백준 1260 DFS와 BFS
프로핌
2023. 8. 16. 10:20
문제
그래프를 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
예제 입력 2
5 5 3
5 4
5 2
1 2
3 4
3 1
예제 출력 2
3 1 2 5 4
3 1 4 2 5
예제 입력 3
1000 1 1000
999 1000
예제 출력 3
1000 999
1000 999
난이도 : 중
소요시간 : 50분
이 문제는 제목처럼 DFS와 BFS를 잘 알고 활용하면 엄청 쉬운 문제이다.
첫번째는 정점의 갯수 두번째는 간선의 갯수 그다음에 시작되는 정점을 입력해
간선의 갯수만큼 정점을 연결한다.
그리고 출력을 할땐 DFS를 먼저 출력한다음에 BFS를 출력한다.
출력을할때 정점을 출력할때는 작은숫자부터 출력하는건 이차원배열로 선언한 다음에 하면
적은숫자가 먼저 출력되기 때문에 상관없다.
DFS는 재귀함수를 이용했고
BFS는 우선순위큐를 이용했다.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace prob1260_DFS와_BFS
{
class Graph
{
int[,] adj;
int lineCount;
bool[] DFSCheck;
bool[] BFSCheck;
public Graph(int a)
{
adj = new int[a, a];
lineCount = a;
DFSCheck = new bool[a];
BFSCheck = new bool[a];
}
public int this[int a, int b]
{
get => adj[a - 1, b - 1];
set => adj[a - 1, b - 1] = value;
}
public void BFS(int start)
{
Queue<int> queue = new Queue<int>();
BFSCheck[start - 1] = true;
queue.Enqueue(start - 1);
while (queue.Count > 0)
{
int now = queue.Dequeue();
Console.Write($"{now + 1} ");
for (int next = 0; next < lineCount; next++)
{
if (adj[now, next] == 0)
continue;
if (BFSCheck[next])
continue;
queue.Enqueue(next);
BFSCheck[next] = true;
}
}
}
public void DFS(int start)
{
int now = start - 1;
DFSCheck[now] = true;
Console.Write($"{now + 1} ");
for(int next = 0; next < lineCount; next++)
{
if (adj[now, next] == 0)
continue;
if (DFSCheck[next])
continue;
DFS(next + 1);
}
}
}
class Program
{
static void Main(string[] args)
{
string[] grapH = Console.ReadLine().Split();
int node = int.Parse(grapH[0]);
int line = int.Parse(grapH[1]);
int first = int.Parse(grapH[2]);
Graph graph = new Graph(node);
for (int i = 0; i < line; i++)
{
string[] arr = Console.ReadLine().Split();
int nodei = int.Parse(arr[0]);
int nodej = int.Parse(arr[1]);
graph[nodei, nodej] = 1;
graph[nodej, nodei] = 1;
}
graph.DFS(first);
Console.WriteLine();
graph.BFS(first);
}
}
}