inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

자바스크립트 알고리즘 문제풀이 입문(코딩테스트 대비)

2. 경로탐색(DFS-인접행렬 : 노드개수가 적을 때)

클래스를 활용해서 만들어보았습니다!

213

YEONGHUN KO
0

저는 matrix말고 list방식으로 그래프를 저장하고 경로를 탐색해보았습니다! 

 class Graph {
        constructor() {
          this.adjacencyList = [];
        }

        addvtx(vtx) {
          if (this.adjacencyList[vtx] in this.adjacencyList) return;
          else {
            this.adjacencyList[vtx] = [];
          }

          return this.adjacencyList;
        }

        addEdge(v1, v2) {
          this.adjacencyList[v1].push(v2);
        }

        searchingPath(start, destination) {
          let tmp = [];
          let result = [];
          let mark = {};

          const dfs = v => {
            var node = this.adjacencyList[v];
            if (!node) return null;

            // 들어오는 족족 tmp에 조합을 넣고
            // mark에 새긴다
            tmp.push(v);
            mark[v] = true;
            if (v === destination) {
              result.push(tmp.slice());
            } else {
              for (var nei of node) {
                if (mark[nei]) {
                  continue;
                } else {
                  dfs(nei);

                  // 끝나면 다시 풀어주고 조합에서 빼버린다.
                  mark[nei] = false;
                  tmp.pop();
                }
              }
            }
          };

          dfs(start);

          return result;
        }
      }

    
      let graph = new Graph();
      graph.addvtx(1);
      graph.addvtx(2);
      graph.addvtx(3);
      graph.addvtx(4);
      graph.addvtx(5);

      graph.addEdge(1, 2);
      graph.addEdge(1, 3);
      graph.addEdge(1, 4);
      graph.addEdge(2, 1);
      graph.addEdge(2, 3);
      graph.addEdge(2, 5);
      graph.addEdge(3, 4);
      graph.addEdge(4, 2);
      graph.addEdge(4, 5);

      graph.searchingPath(1,5)

답변 0