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

2023. 5. 3. 20:41·개발 공부/알고리즘

썸머코딩이 끝난 후 일단 가장 많이 나오는 DFS/BFS 부터 정복하자는 생각으로 풀게 되었다

 

접근 방법

BFS와 DFS 중 고민했는데 DFS로 해서 재귀함수로 하는게 최솟값을 찾는게 더 편하겠다고 생각이 들었다

begin 부터 words의 0번째 배열부터 탐색을 시작해서 1개 빼고 다 같으면 다시 그 단어부터 찾는 방식이다

미리 방문을 표기할 수 있는 배열 visited와 최솟값 변수인 temp를 전역 변수로 선언해 dfs 메소드 내에서도 

사용하게 했다. 

 

package codingtestStudy;

import java.util.*;

public class wordTransformation {
    static boolean[] visited;
    static int temp;
    public static void main(String[] args) {
        int a = solution("hit", "cog", new String[]{"hot", "dot", "dog", "lot", "log", "cog"});
        System.out.println(a);
    }

    public static int solution(String begin, String target, String[] words) {
        int answer = 0;
        temp= Integer.MAX_VALUE;
        visited = new boolean[words.length];
        dfs(begin, target, words, 0);
        return temp;
    }

    static void dfs(String begin, String target, String[] words, int depth) {
        if(begin.equals(target) && temp > depth){
            temp = depth;
        }
        int count;
        for(int i = 0; i < words.length; i++){
                count = 0;
                if(visited[i] == true){
                    continue;
                }
            for(int j = 0; j < begin.length(); j++){
                if(words[i].charAt(j)==begin.charAt(j)){
                    count++;
                }
            }
            if(count == begin.length()-1){
                visited[i] = true;
                dfs(words[i], target, words, depth+1);
            }
            visited[i] = false;
        }
    }


}

'개발 공부 > 알고리즘' 카테고리의 다른 글

백준 1463 '1로 만들기' 자바  (0) 2023.04.26
백준 2252 '줄 세우기' 자바  (0) 2023.04.26
백준 1541 '잃어버린 괄호' 자바  (0) 2023.04.25
백준 1715 '카드 정렬하기' 자바  (0) 2023.04.25
백준 11047 '동전 0' 자바  (0) 2023.04.25
'개발 공부/알고리즘' 카테고리의 다른 글
  • 백준 1463 '1로 만들기' 자바
  • 백준 2252 '줄 세우기' 자바
  • 백준 1541 '잃어버린 괄호' 자바
  • 백준 1715 '카드 정렬하기' 자바
코딩숙
코딩숙
개발이라는 끝이 없는 바다 묵묵히 꾸준히 항해하기
  • 코딩숙
    코딩숙
    코딩숙
  • 전체
    오늘
    어제
    • 분류 전체보기 (63)
      • CS 공부 (17)
        • 클라우드 (3)
        • 네트워크 (3)
      • 개발 공부 (40)
        • 오류 해결 (4)
        • 알고리즘 (12)
        • Spring (3)
        • JPA (2)
        • TIL(오늘 내가 배운 것) (9)
        • 코드복습 (1)
        • 디자인 패턴 (1)
      • IT 관련 영상 메모 (1)
      • 데일리피드백 (0)
      • Tools (1)
      • Wishy (이력서 평가 프로젝트) (3)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    404 Not Found
    302 Found
    변수
    http
    setter method
    innodb
    appsmith
    데이터 타입
    프로그래머스 네트워크 자바
    개발공부
    자바
    isAfter()
    isBefore()
    java
    도메인설계
    JPA
    user mode
    getter method
    데이터베이스 백업
    마이크로서비스
    데이터베이스 손상
    programmers #정수 내림차순으로 배치하기
    프로그래머스
    HTTP BODY
    키 페어 분실
    게임 맵 최단거리 자바
    키 페어 변경
    인프런
    개발자
    백준
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.4
코딩숙
프로그래머스 '단어 변환' 자바
상단으로

티스토리툴바