프로그래머스 단어변환 자바

BioBeBE·2022년 8월 5일
0

프로그래머스

목록 보기
38/40

문제풀이

  1. 모든 경로 탐색을 위한 visit[] 생성
  2. words 내에 target 없으면 0 return
  3. begin과 한글자 차이면 반복하는 DFS 생성, 한글자씩 변화하는 begin과 target 같으면 탐색 Level return

코드

import java.util.*;
class Solution {
    boolean[] visit;
    ArrayList<String> arr;
    int answer = 0;
    public int solution(String begin, String target, String[] words) {
        visit=new boolean[words.length];
        arr= new ArrayList<>();
        boolean check = false;
        for(int i=0;i<words.length;i++){
            if(target.equals(words[i])){
                    check=true;
                }
            }
        if(!check)return 0;
        DFS(begin, target, words, 0);
        
        return answer;
    }
    void DFS(String begin, String target, String[] words, int L){
        if(begin.equals(target)){
            answer=L;
        }else{
            for(int i=0;i<words.length;i++){
                int cnt=0;
                for(int j=0;j<begin.length();j++){
                     
                    if(begin.charAt(j)==words[i].charAt(j))cnt++;
                }
                if(cnt==begin.length()-1 && !visit[i]){
                   
                    visit[i]=true;
                    DFS(words[i], target, words, L+1);
                    visit[i]=false;
                }
            }
        }
    }
}
profile
개발자지망생

0개의 댓글