Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

22.01.18 - [PG] 단어 변환 #196

Closed
suhyunsim opened this issue Jan 17, 2022 · 0 comments
Closed

22.01.18 - [PG] 단어 변환 #196

suhyunsim opened this issue Jan 17, 2022 · 0 comments
Assignees
Labels
DFS 깊이 우선 탐색 lv.3 프로그래머스 - level 3 성공 맞은 문제

Comments

@suhyunsim
Copy link
Owner

문제

핵심 아이디어

  • DFS로 풀이
  • words 길이 최대 50이라서 길이 51의 visited[] 생성
  • dfs로 돌면서 방문했는지, 단어리스트와 비교하는 단어 철자 한 개만 다른지 확인
  • 최대 길이 50 내에 단어 변환 가능하면 해당 카운트 리턴, 그렇지 않으면 0 리턴

어려운 점, 실수

풀이

package main.java.com.poogle.PG.Q43163;

public class Solution {
    static int answer;
    static boolean[] visited;

    public static void main(String[] args) {
        System.out.println(solution("hit", "cog", new String[]{"hot", "dot", "dog", "lot", "log", "cog"}));
        System.out.println(solution("hit", "cog", new String[]{"hot", "dot", "dog", "lot", "log"}));
    }

    public static int solution(String begin, String target, String[] words) {
        answer = 51;
        visited = new boolean[51];
        dfs(begin, target, words, 0);
        return answer == 51 ? 0 : answer;
    }

    private static void dfs(String begin, String target, String[] words, int cnt) {
        if (begin.equals(target)) {
            answer = Math.min(answer, cnt);
            return;
        }
        for (int i = 0; i < words.length; i++) {
            if (!visited[i] && check(begin, words[i])) {
                visited[i] = true;
                dfs(words[i], target, words, cnt + 1);
                visited[i] = false;
            }
        }
    }

    private static boolean check(String begin, String word) {
        int cnt = 0;
        for (int j = 0; j < begin.length(); j++) {
            if (begin.charAt(j) != word.charAt(j)) cnt++;
        }
        return cnt == 1;
    }
}
@suhyunsim suhyunsim added 성공 맞은 문제 lv.3 프로그래머스 - level 3 DFS 깊이 우선 탐색 labels Jan 17, 2022
@suhyunsim suhyunsim added this to the 1월 3주 차 milestone Jan 17, 2022
@suhyunsim suhyunsim self-assigned this Jan 17, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
DFS 깊이 우선 탐색 lv.3 프로그래머스 - level 3 성공 맞은 문제
Projects
None yet
Development

No branches or pull requests

1 participant