Skip to content

Instantly share code, notes, and snippets.

@gjhernandezp
Created November 17, 2015 23:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gjhernandezp/afef15ea542265515a3f to your computer and use it in GitHub Desktop.
Save gjhernandezp/afef15ea542265515a3f to your computer and use it in GitHub Desktop.
FloydWarshall
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" x y u v s \n",
"x [0, 2, 3, 4, 9]\n",
"y [12, 0, 15, 6, 7]\n",
"u [2, 4, 0, 1, 11]\n",
"v [16, 4, 19, 0, 11]\n",
"s [5, 7, 8, 9, 0]\n"
]
}
],
"source": [
"def FloydWarshall(G):\n",
" A=[] # A= (a_{ij}) n×n adjacency matrix of the digraph G\n",
" \n",
" for u in G:\n",
" Au = [] # row of A correponding to vertex u \n",
" for v in G:\n",
" if v in G[u]:Au.append(G[u][v])\n",
" elif u == v : Au.append(0)\n",
" else: Au.append(float(\"inf\")) \n",
" A.append(Au)\n",
" \n",
" Cnext = A\n",
" \n",
" for k in range(len(G)):\n",
" C = Cnext\n",
" for i in range(len(G)):\n",
" for j in range(len(G)):\n",
" if C[i][j] > C[i][k]+ C[k][j]:\n",
" Cnext[i][j] = C[i][k]+ C[k][j]\n",
" return Cnext\n",
" \n",
"G = {'s': {'u':10, 'x':5},\n",
" 'u': {'v':1, 'x':2},\n",
" 'v': {'y':4},\n",
" 'x':{'u':3,'v':9,'y':2},\n",
" 'y':{'s':7,'v':6}}\n",
"\n",
"F = FloydWarshall(G)\n",
"\n",
"V = \" \"\n",
"for u in G:\n",
" V = V + u + \" \"\n",
"print(V)\n",
"\n",
"i = 0\n",
"for u in G:\n",
" print(u,F[:][i])\n",
" i = i + 1\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.4.3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment