Python 通过拥有一个包含迷宫房屋(2维)的列表,我如何使用字典创建一个有向图

Python 通过拥有一个包含迷宫房屋(2维)的列表,我如何使用字典创建一个有向图,python,graph,directed-graph,Python,Graph,Directed Graph,我只能画一个无向图。我不知道我怎么做导演 有什么想法吗?提供了一个关于用python实现图形的很好的教程。从本文中,这是一个由字典表示的目录图示例: graph = {'A': ['B', 'C'], 'B': ['C', 'D'], 'C': ['D'], 'D': ['C'], 'E': ['F'], 'F': ['C']} 也就是说,您可能还希望查看现有的图形库,例如和。因为您已经有了一个列表,请尝

我只能画一个无向图。我不知道我怎么做导演

有什么想法吗?

提供了一个关于用python实现图形的很好的教程。从本文中,这是一个由字典表示的目录图示例:

graph = {'A': ['B', 'C'],
         'B': ['C', 'D'],
         'C': ['D'],
         'D': ['C'],
         'E': ['F'],
         'F': ['C']}

也就是说,您可能还希望查看现有的图形库,例如和。

因为您已经有了一个列表,请尝试创建一个邻接矩阵而不是字典

list_of_houses = []
directed_graph = [][]
for i in xrange(len(list_of_houses)):
    for i in xrange(len(list_of_houses)):
        directed_graph[i][i] = 0
然后,对于从一个房屋到另一个房屋的任何新边缘(或w/e连接)


你完成了。如果从
house\u a
house\u b
有一条边,那么
directed\u graph[house\u a][house\u b]==1

为这篇冗长的文章道歉。我在火车上有时间消磨时间

我猜你要找的是一个有向图,它表示从起始位置开始的所有路径(与迷宫的图表示相反,迷宫的图表示曾经可以用于求解任意起始/结束位置)

(无意冒犯,但)这听起来像是家庭作业,或者至少是一项非常适合做家庭作业的任务。考虑到这一点,以下解决方案侧重于简单性,而不是性能或优雅性

方法 一种简单的方法是首先以更易于导航的格式存储地图,然后从“开始”节点开始执行以下操作:

  • 查找邻居(上、下、左、右)
  • 对于每个邻居:
    • 如果它不是一个可能的路径,请忽略
    • 如果以前处理过此节点,请忽略
    • 否则,将此节点添加为边,并将其推送到队列(不是堆栈,稍后将详细介绍)以进行进一步处理
  • 对于队列/堆栈中的每个节点,重复步骤1
  • (参见下面的示例实现)

    此时,您将以一个开始节点位于树的顶部,结束节点作为一个叶子结束。在这一点上,解决这个问题很容易。看

    在构建图表时,一种可能的优化方法是在找到终点后停止。您将得到一个不完整的图,但如果您只关心最终的解决方案,这并不重要

    堆栈还是队列? 请注意,使用堆栈(先进先出)将意味着以某种方式构建图形,而使用队列(先进先出)将产生一种方法

    你通常想要使用一个队列(宽度优先),如果意图是寻找最短路径。考虑下面的映射:

           START
    ########   ###### 
    ########   ######
    ### b    a ######  
    ###   ##   ######
    ###   ## e ######
    ### c    d ######
    ########   ######
    ########      END
    #################
    
    如果路径是深度优先遍历的,并且在分支
    a
    处,您恰好在
    a->e
    之前选择
    a->b
    路径,您将得到以下图形:

     START
       |
       a
      / \
     b   e   <-- end, since d already visited
     |
     c
     |
     d
      \
       END
    
    示例代码 提供的示例输入:

    ..........
    #########.
    ..........
    .#########
    ......#...
    #####...#.
    ##...####.
    ##.#......
    ...#######
    
    e = (0,0)
    s = (8,0)
    
    免责声明:以下代码是为了清晰而不是为了速度而编写的。它没有经过全面测试,因此不能保证正确性,但它应该让您了解可能的情况

    我们假设输入文件的格式是一致的。为了简洁起见,大多数错误检查都省略了

    # regex to extract start/end positions
    import re
    re_sepos = re.compile("""
        ^([se])\s* # capture first char (s or e) followed by arbitrary spaces
        =\s*        # equal sign followed by arbitrary spaces
        \(          # left parenthesis
        (\d+),(\d+) # capture 2 sets of integers separated by comma
        \)          # right parenthesis
    """, re.VERBOSE)
    
    def read_maze(filename):
        """
        Reads input from file and returns tuple (maze, start, end)
          maze : dict holding value of each maze cell { (x1,y1):'#', ... }
          start: start node coordinage (x1,y1)
          end  : end node coordinate (x2,y2)
        """
        # read whole file into a list
        f = open(filename, "r")
        data = f.readlines()
        f.close()
    
        # parse start and end positions from last 2 lines
        pos = {}
        for line in data[-2:]: 
            match = re_sepos.match(line)
            if not match:
                raise ValueError("invalid input file")
            c,x,y = match.groups() # extract values
            pos[c] = (int(x),int(y))
        try:
            start = pos["s"]
            end   = pos["e"]
        except KeyError:
            raise ValueError("invalid input file")
    
        # read ascii maze, '#' for wall '.' for empty slor 
        # store as maze = { (x1,y1):'#', (x2,y2):'.', ... }
        # NOTE: this is of course not optimal, but leads to a simpler access later 
        maze = {}
        for line_num, line in enumerate(data[:-3]): # ignore last 3 lines
            for col_num, value in enumerate(line[:-1]): # ignore \n at end
                maze[(line_num, col_num)] = value
    
        return maze, start, end
    
    def maze_to_dag(maze, start, end):
        """
        Traverses the map starting from start coordinate.
        Returns directed acyclic graph in the form {(x,y):[(x1,y1),(x2,y2)], ...}
        """
        dag = {}        # directed acyclic graph
        queue = [start] # queue of nodes to process
    
        # repeat till queue is empty
        while queue:
            x,y = queue.pop(0)      # get next node in queue
            edges = dag[(x,y)] = [] # init list to store edges
    
            # for each neighbour (top, bottom, left, right)
            for coord in ((x,y-1), (x,y+1), (x-1,y), (x+1,y)): 
                if coord in dag.keys(): continue   # visited before, ignore
    
                node_value = maze.get(coord, None) # Return None if outside maze
                if node_value == ".": # valid path found
                    edges.append(coord) # add as edge
                    queue.append(coord) # push into queue
    
                    # uncomment this to stop once we've found the end point
                    #if coord == end: return dag
    
        return dag
    
    if __name__ == "__main__":
        maze,start,end = read_maze("l4.txt")
        dag = maze_to_dag(maze, start, end)
        print dag
    

    你的问题是什么?是吗"如何使用字典或其他工具实现有向图?事实上,不是这样。我无法创建表示有向图的字典。这不是我的问题。我的问题是创建表示该图的字典。我可以创建无向图。有向图,没有那么多。再次重新措辞。我有一个表示有向图的列表这是一个二维迷宫的所有坐标。我很难从那里得到一个有向图。我只能做一个无向图。上面的例子是一个有向图。如果你能提供一个例子,说明你到目前为止有什么问题,以及你面临什么问题,我们会帮助得更好。你能给出一个你拥有的数据的例子吗?我收到一封邮件我用迷宫的坐标做了一个新的列表。然后我试着编一本字典,但失败得很惨:
    ..........
    #########.
    ..........
    .#########
    ......#...
    #####...#.
    ##...####.
    ##.#......
    ...#######
    
    e = (0,0)
    s = (8,0)
    
    # regex to extract start/end positions
    import re
    re_sepos = re.compile("""
        ^([se])\s* # capture first char (s or e) followed by arbitrary spaces
        =\s*        # equal sign followed by arbitrary spaces
        \(          # left parenthesis
        (\d+),(\d+) # capture 2 sets of integers separated by comma
        \)          # right parenthesis
    """, re.VERBOSE)
    
    def read_maze(filename):
        """
        Reads input from file and returns tuple (maze, start, end)
          maze : dict holding value of each maze cell { (x1,y1):'#', ... }
          start: start node coordinage (x1,y1)
          end  : end node coordinate (x2,y2)
        """
        # read whole file into a list
        f = open(filename, "r")
        data = f.readlines()
        f.close()
    
        # parse start and end positions from last 2 lines
        pos = {}
        for line in data[-2:]: 
            match = re_sepos.match(line)
            if not match:
                raise ValueError("invalid input file")
            c,x,y = match.groups() # extract values
            pos[c] = (int(x),int(y))
        try:
            start = pos["s"]
            end   = pos["e"]
        except KeyError:
            raise ValueError("invalid input file")
    
        # read ascii maze, '#' for wall '.' for empty slor 
        # store as maze = { (x1,y1):'#', (x2,y2):'.', ... }
        # NOTE: this is of course not optimal, but leads to a simpler access later 
        maze = {}
        for line_num, line in enumerate(data[:-3]): # ignore last 3 lines
            for col_num, value in enumerate(line[:-1]): # ignore \n at end
                maze[(line_num, col_num)] = value
    
        return maze, start, end
    
    def maze_to_dag(maze, start, end):
        """
        Traverses the map starting from start coordinate.
        Returns directed acyclic graph in the form {(x,y):[(x1,y1),(x2,y2)], ...}
        """
        dag = {}        # directed acyclic graph
        queue = [start] # queue of nodes to process
    
        # repeat till queue is empty
        while queue:
            x,y = queue.pop(0)      # get next node in queue
            edges = dag[(x,y)] = [] # init list to store edges
    
            # for each neighbour (top, bottom, left, right)
            for coord in ((x,y-1), (x,y+1), (x-1,y), (x+1,y)): 
                if coord in dag.keys(): continue   # visited before, ignore
    
                node_value = maze.get(coord, None) # Return None if outside maze
                if node_value == ".": # valid path found
                    edges.append(coord) # add as edge
                    queue.append(coord) # push into queue
    
                    # uncomment this to stop once we've found the end point
                    #if coord == end: return dag
    
        return dag
    
    if __name__ == "__main__":
        maze,start,end = read_maze("l4.txt")
        dag = maze_to_dag(maze, start, end)
        print dag