首页 > 解决方案 > 遍历json模式?

问题描述

我创建了一个 json 模式,以这种格式表示岛屿地图以及它们之间的连接:

MAP:{ sky: [ 'valley' ],
  valley: [ 'koopa' ],
  mushroom: [ 'toad' ],
  toad: [ 'koopa' ],
  koopa: [],
  twin: [ 'valley' ],
  forest: [ 'twin' ] }

我有一个位置A和一个目的地B;知道地图中始终存在路径,我需要创建一个函数来查找地图中从 A 到 B 的路径吗?

我的代码:

 Graph.prototype.getHimHome = function (position, destination, n){
      const arr = this.adjList;
      let isHome = false;
      let path = [destination];

        while( !isHome &&  n>0) {

            for( el in arr) { // looping through the json schemma
                      arr[el].forEach( element => {
                          if(element === path[path.length - 1])//this means we're on the path;
                          {
                            path.push(el);
                          } else {
                            path.push(el);
                          }
                      })
                } ;


            if(path[path.length - 1] === position){
              isHome = true;
            }
            n--;
          }

      console.log(path);

      }

标签: javascriptgraph-algorithm

解决方案


推荐阅读