[중급] DFS와 BFS

2022. 1. 12. 21:20·알고리즘

DFS와 BFS는 대표적인 그래프 탐색 알고리즘이다.

*탐색 : 많은 양의 데이터 중에서 원하는 데이터를 찾는 과정을 말함

 

깊이 우선 탐색 DFS(DEPTH - FIRST SEARCH)

: 탐색 노드(루트 노드 or 다른 노드)에서 시작하여 다음 분기로 넘어가기 전에 해당 분기를 완벽하게 탐색하는 방법

 

DFS 구현 방법

- 재귀함수

- 스택  (되돌아가기 위해 스택 필요)

 

 

1) 재귀함수

-Linkedlist 이용

package dd;
import java.util.*;
public class Main {
	public static void dfs_list(int v,LinkedList<Integer>[] adjList,boolean[] visited)
	{
		visited[v]=true;
		System.out.print(v+" ");
		Iterator<Integer> iter = adjList[v].listIterator(); //정점 인접리스트
		while(iter.hasNext()) {
			int w= iter.next();
			if(!visited[w]) {
				dfs_list(w,adjList,visited);
			}
		}
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc=new Scanner(System.in);
		int n=sc.nextInt(); //정점
		int m=sc.nextInt(); //간선
		int v= sc.nextInt(); //탐색을 시작할 정점의 번호
		boolean visited[] = new boolean[n+1]; //방문 여부를 검사할 배열
		LinkedList<Integer>[] adjList = new LinkedList[n+1];
		for(int i=0;i<=n;i++) {
			adjList[i]=new LinkedList<Integer>();
		}
		//두 정점 사이에 여러개 간선이 있을 수 있음
		// 입력으로 주어지는 간선은 양방향
		for(int i=0;i<m;i++) {
			int v1 = sc.nextInt();
			int v2= sc.nextInt();
			adjList[v1].add(v2);
			adjList[v2].add(v1);
		}
		for(int i=1;i<=n;i++) {
			Collections.sort(adjList[i]);
		}
		boolean[] check = new boolean[n+1];
		System.out.println("DFS-인접리스트");
		dfs_list(v,adjList,check);
	}

}

2) 스택

 

public void DFS(int start){
    boolean[] visited = new boolean[vertex];
    Stack<Integer> stack = new Stack<Integer>();
    stack.push(start);
    while (!stack.isEmpty()){
        int v = stack.pop();
        if (!visited[v]){
            visited[v] = true;
            for (int i = 0; i < list[v].size(); i++){
                int dest = list[v].get(i);
                if (!visited[dest])
                    stack.push(dest);
            }
        }
    }
}

 

너비 우선 탐색 BFS(Breadth-First Search)

: 탐색 노드에서 시작해서 인접한 노드를 먼저 탐색하는 방법 시작 정점으로부터 가까운 정점을 먼저 방문하고 멀리 떨어져 있는 정점을 나중에 방문하는 순회 방법, 즉 거리가 d인 정점들을 모두 방문하고 d+1의 거리를 갖는 노드들 방문

 

BFS 구현 방법

- 큐를 사용하여 구현됨

 

큐를 이용한 BFS

1) 큐

public static void bfs_list(int v, LinkedList<Integer>[] adjList, boolean[] visited) {
	Queue<Integer> queue = new LinkedList<Integer>();
	visited[v] = true; 
	queue.add(v);

	while(queue.size() != 0) { 
		v = queue.poll(); 
		System.out.print(v + " ");

		Iterator<Integer> iter = adjList[v].listIterator();
		while(iter.hasNext()) { 
			int w = iter.next(); 
			if(!visited[w]) { 
				visited[w] = true; 
				queue.add(w); 
			} 
		}
	}
}

+) 인접행렬

public static void bfs_array(int v, int[][] adjArray, boolean[] visited) {
	Queue<Integer> q = new LinkedList<>();
	int n = adjArray.length - 1;

	q.add(v);
	visited[v] = true;

	while (!q.isEmpty()) {
		v = q.poll();
		System.out.print(v + " ");

		for (int i = 1; i <= n; i++) {
			if (adjArray[v][i] == 1 && !visited[i]) {
				q.add(i);
				visited[i] = true;
			}
		}
	}
}

* 인접행렬은 간선들을 저장하는 방식의 일부인거지 bfs를 구현하는 방식이 아님

 

 

🙌 참고 및 출처

https://minhamina.tistory.com/36

 

[Java] BFS 너비 우선 탐색 - 인접리스트 / 인접행렬로 구현

BFS 너비 우선 탐색(Breadth First Search) "꼼꼼하게 좌우를 살피며 다니자"와 같이 시작 정점으로부터 가까운 정점을 먼저 방문하고 멀리 떨어져 있는 정점을 나중에 방문하는 알고리즘이다. 시작 정

minhamina.tistory.com

 

'알고리즘' 카테고리의 다른 글

이진탐색  (1) 2023.01.25
정렬  (1) 2023.01.19
DFS / BFS  (0) 2023.01.12
구현  (0) 2023.01.12
Greedy  (0) 2023.01.11
'알고리즘' 카테고리의 다른 글
  • 정렬
  • DFS / BFS
  • 구현
  • Greedy
gani+
gani+
꾸준히 기록할 수 있는 사람이 되자 !
  • gani+
    Gani_Dev :)
    gani+
  • 전체
    오늘
    어제
    • 분류 전체보기 (43)
      • 당장 프로젝트 (2)
        • 트러블슈팅 (0)
      • 댕댕어디가 프로젝트 (11)
        • 트러블슈팅 (3)
        • MSA (8)
      • 개발일지 (2)
      • BOOK (12)
        • SQL 레벨업 (10)
      • 프로젝트 (0)
      • ELK (5)
      • 알고리즘 (9)
      • CS (2)
        • 디자인패턴 (2)
  • 블로그 메뉴

    • 홈
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    DP
    다익스트라
    백준4963
    플로이드워셔
    이것이 코딩 테스트다
    최단경로
    SWMaestro14
    dfs
    이진탐색
    14기
    순차탐색
    완전탐색
    4673
    후기
    4963
    정렬
    SW마에스트로
    소마
    이것이코딩테스트다
    다이나믹프로그래밍
    백준
    9095
    해쉬
    알고리즘
    섬의개수
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
gani+
[중급] DFS와 BFS
상단으로

티스토리툴바