如何在不搜索的情况下在networkx中找到最短路径?

时间:2019-02-12 21:43:56

标签: python python-3.x graph networkx

我有一个典型的图,它是一棵树,我可以找到两个节点之间的最短路径:

nx.shortest_path(G, source=root, target=target)

但是我不知道是否有一个简单的函数不允许向后搜索。也就是说,输入为:

nx.shortest_path(G, 5, 10)
  

[5,6,10]

它向前看(在树下),但是如果

nx.shortest_path(G, 5, 3)
  

[5,3]

它返回树,但应给出None。

我的问题是:有什么简单的方法可以退出,或者我只需要实现一个自定义功能来检查此问题?

1 个答案:

答案 0 :(得分:1)

如评论中所述,图形中没有“向上”或“向下”。您可以使用类ExpensesDataSource _expensesDataSource = ExpensesDataSource([expense]); Widget getDataTable() { return PaginatedDataTable( header: Text('Despesas', style: TextStyle(color: Color(0xFF4C4C4C), fontWeight: FontWeight.bold, fontSize: 15),), columns: <DataColumn>[ DataColumn( label: Text("Data"), numeric: false, ), DataColumn( label: Text("Descrição"), numeric: false, ), DataColumn( label: Text("Total"), numeric: false, ), ], source: _expensesDataSource, ); } class ExpensesDataSource extends DataTableSource { List<Expense> _expenses = <Expense>[]; int _selectedCount = 0; ExpensesDataSource(List<Expense> listExpenses) { this._expenses = listExpenses; } @override DataRow getRow(int index) { final Expense expense = _expenses[index]; return DataRow.byIndex( index: index, onSelectChanged: (bool value) { print('Row selected: $value ${expense.name}'); }, cells: [ DataCell(Text(expense.date)), DataCell(Text(expense.name)), DataCell(Text(Utils.convert2currency(expense.total_amount))) ] ); } @override // TODO: implement rowCount int get rowCount => _expenses.length; @override bool get isRowCountApproximate => false; @override int get selectedRowCount => _selectedCount; } 创建一个有向图,当您尝试查找沿边缘方向的路径时,会出现错误“ NetworkXNoPath:3与1之间没有路径”。在这种情况下,您可以使用DiGraph()来捕获异常:

try

或者,您可以检查两个顶点是否完全具有任何路径:

import networkx as nx
from networkx import NetworkXNoPath

G = nx.DiGraph([(1, 2), (2, 3), (4,2)]) # create a directed graph

nx.shortest_path(G, source=1, target=3)
# [1, 2, 3]

try:
    path = nx.shortest_path(G, source=3, target=1)
except NetworkXNoPath:
    path = None

Directed Graph