SMALL
https://www.acmicpc.net/problem/1260
1260번: DFS와 BFS
첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사
www.acmicpc.net
- 문제
- 문제풀이
정점의 수, 간선의 수, 시작 정점을 받아준 후 간선정보를 입력한 뒤 각각 BFS와 DFS를 시행해준다.
- 코드 1
namespace YONGYONG2
{
using System;
using System.Collections.Generic;
public class Program
{
static int N;
static int[,] Graph;
static bool[] DFSbool;
static bool[] BFSbool;
public static void DFS(int N,int V)
{
DFSbool[V] = true;
Console.Write(V + " ");
for(int i=1;i<=N;i++)
{
if (Graph[V, i] == 1 && !DFSbool[i])
{
DFS(N,i);
}
}
}
public static void BFS(int N,int V)
{
Queue<int> queue = new Queue<int>();
queue.Enqueue(V);
BFSbool[V] = true;
Console.Write(V + " ");
while (queue.Count != 0)
{
int temp= queue.Dequeue();
for(int i = 1; i <= N; i++)
{
if (Graph[temp, i] == 1 && !BFSbool[i])
{
queue.Enqueue(i);
Console.Write(i+" ");
BFSbool[i] = true;
}
}
}
}
public static void Main(string[] args)
{
string[] input = Console.ReadLine().Split(' ');
N = int.Parse(input[0]);
int M = int.Parse(input[1]);
int V = int.Parse(input[2]);
Graph= new int[N+1, N+1];
DFSbool=new bool[N+1];
BFSbool = new bool[N + 1];
for(int i = 0; i < M; i++)
{
string[] line = Console.ReadLine().Split();
int a = int.Parse(line[0]);
int b = int.Parse(line[1]);
Graph[a, b] = 1;
Graph[b, a] = 1;
}
DFS(N, V);
Console.WriteLine();
BFS(N, V);
}
}
}
- 후기
DFS와 BFS는 잊으면 안되겠다.
LIST
'백준 > C#' 카테고리의 다른 글
[C#]백준 24444번: 알고리즘 수업 - 너비 우선 탐색 1 (0) | 2023.03.05 |
---|---|
[C#]백준 24479번: 알고리즘 수업-깊이 우선 탐색 1 (0) | 2023.03.05 |
[C#]백준 1920번: 수 찾기 (0) | 2023.02.19 |
[C#]백준 9020번: 골드바흐의 추측 (0) | 2023.02.05 |
[C#]백준 6198번: 옥상 정원 꾸미기 (0) | 2023.02.05 |