Programmers - BFS/DFS

zwundzwzig·2023년 8월 4일
0

algorithm

목록 보기
9/12
post-thumbnail

네트워크

public class Solution {
    static int solution(int n, int[][] computers) {
        int answer = 0;
        boolean[] visited = new boolean[n];
        for (int i = 0; i < n; i++){
            if (!visited[i]){
                answer++;
                dfs(i, visited, computers);
            }
        }
        return answer;
    }

    static void dfs(int node, boolean[] visited, int[][] computers){
        visited[node] = true;
        for (int i = 0; i < computers.length; i++){
            if (computers[node][i] == 1 && !visited[i]) {
                dfs(i, visited, computers);
            }
        }
    }
}

단어변환

import java.util.LinkedList;
import java.util.Queue;

public class Solution {

    static class Node {
        String value;
        int edge;

        public Node(String value, int edge) {
            this.value = value;
            this.edge = edge;
        }
    }

    public int solution(String begin, String target, String[] words) {
        int n = words.length, ans = 0;
        Queue<Node> q = new LinkedList<>();
        boolean[] visit = new boolean[n];
        q.add(new Node(begin, 0));

        while (!q.isEmpty()) {
            Node cur = q.poll();
            if (cur.value.equals(target)) {
                ans = cur.edge;
                break;
            }

            for (int i = 0; i < n; i++) {
                if (!visit[i] && isNext(cur.value, words[i])) {
                    visit[i] = true;
                    q.add(new Node(words[i], cur.edge + 1));
                }
            }
        }
        return ans;
    }

    static boolean isNext(String current, String next) {
        int cnt = 0;
        for (int i = 0; i < next.length(); i++) {
            if (current.charAt(i) != next.charAt(i)) {
                if (++cnt > 1) return false;
            }
        }
        return true;
    }
}

타겟 넘버

public class Solution {
    static int answer = 0;

    static int solution(int[] numbers, int target) {
        int depth = 0;
        dfs(0, numbers, target, depth);
        return answer;
    }

    static void dfs(int prev, int[] numbers, int target, int depth) {
        if (depth == numbers.length && prev == target) answer++;
        else {
            dfs(prev + numbers[depth], numbers, target, depth + 1);
            dfs(prev - numbers[depth], numbers, target, depth + 1);
        }
    }
}
profile
개발이란?

2개의 댓글

comment-user-thumbnail
2023년 8월 4일

정리가 잘 된 글이네요. 도움이 됐습니다.

답글 달기
comment-user-thumbnail
2023년 8월 5일

👍

답글 달기