Graph 如何将迷宫转换为图形?

Graph 如何将迷宫转换为图形?,graph,maze,Graph,Maze,我正在尝试将迷宫数据结构转换为图形。迷宫就像一个网格,细胞之间有一些墙 maze[8][8][4] is how the maze is represented. If maze[i][j][0] = 1 it means you can't go up from (i,j) if maze[i][j][1] = 1 it means you can't go down from (i,j) // and so on 我想把这个迷宫转换成一个图形,我该怎么做呢?你可以用两种方法来完成: 1.从

我正在尝试将迷宫数据结构转换为图形。迷宫就像一个网格,细胞之间有一些墙

maze[8][8][4] is how the maze is represented.
If maze[i][j][0] = 1 it means you can't go up from (i,j)
if maze[i][j][1] = 1 it means you can't go down from (i,j)
// and so on

我想把这个迷宫转换成一个图形,我该怎么做呢?

你可以用两种方法来完成:

1.从初始矩阵创建邻接矩阵。邻接矩阵的形式如下:


2.为每个节点创建邻居列表:
j
位于
i
的邻居列表中,如果
i
j
之间存在直接链接,则对于每个邻居单元,如果它们之间没有墙,则使它们在图中连接。

将输入数据视为邻接矩阵。将迷宫视为一条路径,每个连接段在其中创建顶点。每个角点都是一个节点(包括开始和结束)。如果存在连接,则矩阵中有一个值。如果没有,您可以使用INF或-1来判断没有路由。无论如何,你可以用Dijkstra的最短数学算法来解决这个问题。网上有很多关于它的信息


我添加了大小为1的填充,以使代码更简单,迷宫的实际大小将是(第1行,cols-1),

请记住,如果h[I][j]==h[j][I],您只需要存储/计算矩阵的一半。有关在考虑内存效率时选择什么的一些信息,请参阅
h[i][j] = 0, if there is no direct link from i to j 
(i and j are not neighbors in the maze)
h[i][j] = 1, if there is a direct link from i to j 
(i and j are neighbors in the maze)
    game=[[1,1,1,1,1,1,1],
         [1,'A',1,1,0,0,1],
         [1,0,0,0,0,1,1],
         [1,0,0,1,1,1,1],
         [1,1,0,0,0,'B',1],
         [1,1,1,1,1,1,1]]
    rows=len(game)
    cols=len(game[0])
    graph={}
    for i in range(1,rows-1):
       for i in range(1,rows-1):
          if(game[i][j]!=1):
          adj=[]
          for ele in [(i-1,j),(i+1,j),(i,j-1),(i,j+1)]:
               if game[ele[0]][ele[1]] == 0 or game[ele[0]][ele[1]]=='B' :
                       adj.append((ele[0],ele[1]))
          graph[(i,j)]=adj
    print(graph)

    {(1, 1): [(2, 1)],
    (1, 4): [(2, 4), (1, 5)],
    (1, 5): [(1, 4)],
    (2, 1): [(3, 1), (2, 2)],
    (2, 2): [(3, 2), (2, 1), (2, 3)],
    (2, 3): [(2, 2), (2, 4)],
    (2, 4): [(1, 4), (2, 3)],
    (3, 1): [(2, 1), (3, 2)],
    (3, 2): [(2, 2), (4, 2), (3, 1)],
    (4, 2): [(3, 2), (4, 3)],
    (4, 3): [(4, 2), (4, 4)],
    (4, 4): [(4, 3), (4, 5)],
    (4, 5): [(4, 4)]}