如何从2D数组构建图形?

时间:2013-11-20 20:32:32

标签: arrays algorithm graph

我正在尝试学习图形结构和算法。从概念上讲,我理解DFS,BFS,我可以提供图表来实现它们,但传统上如何组成图形?

通常我将它们看作是带有边缘作为指针的节点列表,带有它们连接的节点的边缘列表,或者是两个arr [node_a] [node_b]的交集是边缘权重的2d矩阵。 / p>

当涉及到实际构建输入时,我不知道从哪里开始。

作为一个例子,当你提供2d网格(一个在线pacman问题)时,你将如何构建图形,其中P是源节点,-s是树中的节点。

%%%%%%%%%%%%%%%%%%%%
%--------------%---%
%-%%-%%-%%-%%-%%-%-%
%--------P-------%-%
%%%%%%%%%%%%%%%%%%-%
%.-----------------%
%%%%%%%%%%%%%%%%%%%%

或者,如果提供邻接列表,您将如何构建它?

我理解这可能是一个很大的问题,因为主题相当复杂。赞赏文档的链接!我从介绍层面找不到任何东西。

2 个答案:

答案 0 :(得分:1)

图表通常使用以下两种数据结构之一进行存储:

  1. 邻接列表(http://en.wikipedia.org/wiki/Adjacency_list

  2. 邻接矩阵(http://en.wikipedia.org/wiki/Adjacency_matrix

  3. 每个人都有自己的空间和时间优势。

    您必须将要表示的任何输入转换为图形(例如,将其解析)转换为上述数据结构之一。

答案 1 :(得分:0)

为此,我编写了此javascript,它在权重图中转换了一个矩阵(数组数组)。它开始沿四个方向(向上/向下/向右/向左)导航,而无需走到原处。

然后,它将使用DFS查找最短路径。

const wall = 0
const flat = 1
const target = 9

// no diagonals
const possibleMoves = [
  [-1, 0], // nord
  [0, +1],
  [+1, 0], // sud
  [0, -1],
]

function pathFinder(map) {
  const gridW = map[0].length
  const gridH = map.length
  const start = buildNode([0, 0], map)
  const tree = buildTreeMap(start, map, [start])
  const path = navigateTree(tree)
  console.log(path.map(_ => _.point));
  return path.length


  // Depth-first search (DFS)
  function navigateTree(node) {
    const dfp = (acc, _) => {
      if (_.value === target) {
        acc.push(_)
        return acc
      }
      const targetInMyChildren = _.children.reduce(dfp, [])
      if (targetInMyChildren.length > 0) {
        targetInMyChildren.unshift(_)
        return targetInMyChildren
      }
      return acc
    }

    return node.children.reduce(dfp, [])
  }

  function buildTreeMap(node, map2d, visited) {
    const [x, y] = node.point
    node.children = possibleMoves
      .map((([incx, incy]) => [x + incx, y + incy]))
      .filter(([nx, ny]) => {
    /**
     * REMOVE
     * + out of grid
     * + walls
     * + already visited points
     */
        if (nx < 0 || nx >= gridW
          || ny < 0 || ny >= gridH
          || map2d[ny][nx] === wall) {
          return false
        }

        return visited.findIndex(vis => vis.point[0] === nx && vis.point[1] === ny) === -1
      })
      .map(_ => {
        const newNode = buildNode(_, map2d)
        visited.push(newNode)
        return newNode
      })
    node.children.forEach(_ => buildTreeMap(_, map2d, visited))
    return node
  }

}

function buildNode(point, map) {
  const value = map[point[1]][point[0]]
  return {
    point,
    value,
    children: []
  }
}



const stepsCount = pathFinder([
  [1, 1, 1, 1],
  [0, 1, 1, 0],
  [0, 1, 1, 0],
  [0, 1, 0, 0],
  [0, 1, 1, 1],
  [0, 1, 1, 1],
  [9, 0, 1, 1],
  [1, 1, 1, 1],
  [1, 0, 1, 0],
  [1, 1, 1, 1]
])
console.log(stepsCount);
相关问题