WonYong-Jang / algorithm

0 stars 0 forks source link

dfs(depth first search) / bfs(breadth first search) #2

Open WonYong-Jang opened 6 years ago

WonYong-Jang commented 6 years ago

dfs

==> 스택 으로도 구현 가능!!!! 알아보기

public static int[][] map = new int[1002][1002]; // 인접 행렬
public static int[] visited = new int[1002]; // 방문 기록 
public static void dfs(int v) {

    if(visited[v] == 1 ) return; // base case 
    visited[v] = 1; // 방문 체크
    System.out.print(v+" ");
    for(int i= 1; i<= V ; i++) {
        if(map[v][i] == 1) { 
            dfs(i); //  다음 노드로 이동
        }
    }

}
public static void bfs(int v) {
    Queue<Integer> que = new LinkedList<Integer>();
    que.add(v); // 시작점 
    visited[v]=1;

    while(!que.isEmpty()) {
        int num = que.peek();
        System.out.print(num+" ");
        que.poll();

        for(int i= 1; i<= V ; i++) {
            if(map[num][i] == 1 && visited[i] == 0) { // 방문 기록이 없다면
                visited[i] = 1;
                que.add(i);
            }
        }
    }
}