python文字转图片_python-将文本文件转换为图形

在问题81中,您只能向右或向下移动.因此,您的Dijkstra算法需要一个有向图.如果您将字典用作图,则该字典中的每个值(列表)都不得超过2个节点(您只能在2个方向上移动-> 2个邻居).您可以删除@AustinHastings的最后一段代码中的前两个if块.否则,您将向四个方向移动,并且将获得不同的结果.这是问题81中示例的解决方案.我使用了networkx和jupyter notebook软件包:

import networkx as nx

import numpy as np

import collections

a = np.matrix("""131 673 234 103 18;

201 96 342 965 150;

630 803 746 422 111;

537 699 497 121 956;

805 732 524 37 331""")

rows, columns = a.shape

# Part of @AustinHastings solution

graph = collections.defaultdict(list)

for r in range(rows):

for c in range(columns):

if c < columns - 1:

# get the right neighbor

graph[(r, c)].append((r, c+1))

if r < rows - 1:

# get the bottom neighbor

graph[(r, c)].append((r+1, c))

G = nx.from_dict_of_lists(graph, create_using=nx.DiGraph)

weights = {(row, col): {'weight': num} for row, r in enumerate(a.tolist()) for col, num in enumerate(r)}

nx.set_node_attributes(G, values=weights)

def weight(u, v, d):

return G.nodes[u].get('weight')/2 + G.nodes[v].get('weight')/2

target = tuple(i - 1 for i in a.shape)

path = nx.dijkstra_path(G, source=(0, 0), target=target, weight=weight)

print('Path: ', [a.item(i) for i in path])

%matplotlib inline

color_map = ['green' if n in path else 'red' for n in G.nodes()]

labels = nx.get_node_attributes(G, 'weight')

pos = {(r, c): (c, -r) for r, c in G.nodes()}

nx.draw(G, pos=pos, with_labels=True, node_size=1500, labels = labels, node_color=color_map)

输出:

Path: [131, 201, 96, 342, 746, 422, 121, 37, 331]

vRBhz.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值