공부/C#

[C#] 프로그래머스 BFS 연습 - 단어 변환

굴러다니다니 2025. 3. 7. 12:21
728x90
using System;
using System.Collections.Generic;

public class Solution {
    public bool canChange(string a, string b){
        int same = 0;
        for (int i =0; i < a.Length; i++){
            if (a[i] == b[i]) same++;
        }
        if(same == a.Length-1) return true;
        return false;
    }
    
    public int solution(string begin, string target, string[] words) {
        Queue<(string, int)> queue = new Queue<(string, int)>();
        queue.Enqueue((begin, 0));
        
        bool[] visited = new bool[words.Length];
        while(queue.Count > 0){
            var (a,b) = queue.Dequeue();
            if (a == target){
                return b;
            }
            for(int i =0 ; i < words.Length; i++){
                if (!visited[i] && canChange(a, words[i])){
                    visited[i] = true;
                    queue.Enqueue((words[i], b+1));
                }
            }
        }
        return 0;
    }
}

 

사실 챗 지피티랑 이론적으로 머리 합친거를 혼자 코드로 옮겨 썼다...

 

728x90