001 // GraphLab Project: http://graphlab.sharif.edu 002 // Copyright (C) 2008 Mathematical Science Department of Sharif University of Technology 003 // Distributed under the terms of the GNU Lesser General Public License (LGPL): http://www.gnu.org/licenses/ 004 005 package graphlab.library.algorithms.shortestpath; 006 007 008 import graphlab.library.BaseEdge; 009 import graphlab.library.BaseGraph; 010 import graphlab.library.BaseVertex; 011 012 import java.util.Iterator; 013 014 /** 015 * This method finds the shortest paths between any two vertices of 016 * a graph. 017 * 018 * @author Soroush Sabet, edited by Omid Aladini 019 */ 020 public class FloydWarshall<VertexType extends BaseVertex, 021 EdgeType extends BaseEdge<VertexType>> { 022 /** 023 * @param graph 024 * @return 025 */ 026 public Integer[][] getAllPairsShortestPath(final BaseGraph<VertexType, EdgeType> graph) { 027 028 final Integer dist[][] = new Integer[graph.getVerticesCount()][graph.getVerticesCount()]; 029 Iterator<EdgeType> iet = graph.edgeIterator(); 030 EdgeType edge; 031 for (Integer i : dist[0]) 032 for (Integer j : dist[0]) { 033 dist[i][j] = Integer.MAX_VALUE; 034 } 035 036 while (iet.hasNext()) { 037 edge = iet.next(); 038 dist[edge.target.getId()][edge.source.getId()] = edge.getWeight(); 039 } 040 041 for (VertexType v : graph) 042 for (VertexType u : graph) 043 for (VertexType w : graph) { 044 if ((dist[v.getId()][w.getId()] + dist[w.getId()][u.getId()]) < dist[v.getId()][u.getId()]) 045 dist[v.getId()][u.getId()] = dist[v.getId()][w.getId()] + dist[w.getId()][u.getId()]; 046 } 047 048 return dist; 049 050 } 051 052 }