타겟 넘버 - 프로그래머스

자몽·2022년 2월 10일
1

타겟 넘버 [프로그래머스]

링크

https://programmers.co.kr/learn/courses/30/lessons/43163?language=javascript

코드

function solution(begin, target, data) {
    const words = data
    words.unshift(begin)
    console.log('w',words)
    let graph = {}
    
    let count = 1;
    
    for(let k=0;k<words.length;k++){
        let temp = []
        words.map((word,index)=>{
            let cnt = words[k].length;
            word = word.split("")
            words[k].split("").map((d,i)=>{
                if (d === word[i])
                    cnt--;
            })
        if(cnt===1) temp.push(word.join(""))
        })
        graph[words[k]]=temp
    }
    console.log('graph',graph)

    function bfs(graph, node, visited) {
      const queue = [node];
      visited[node] = true;
      while (queue.length !== 0) {
        console.log(queue)

        const temp = queue.shift();
        console.log(temp,count,graph[temp]);
        if(graph[temp].find(el=>el===target)){
          return;
        }

        graph[temp].forEach((n,index) => {
          if (visited[n]===false) {

              queue.push(n);
            visited[n] = true;
            if (index + 1 === graph[temp].length) {
                count++;
            }
          }
        })
        if(queue.length===0 && node!==target){
            count = 0;
            return;
        }
      }
    }

    const visited = Object.keys(graph).reduce(function(target, key, index) {
      target[key] = false;
      return target;
    }, {})


    bfs(graph,begin,visited)
    return count;
}
profile
꾸준하게 공부하기

0개의 댓글