求無向圖中任意兩點之間最短距離
java
在本例中,假設求1->2之間的最短距離,很容易獲得f(2) = min{f(3)+1,f(5)+1}
f(d) = min(f(0)>0->f(0)+1...f(d-1)>0->f(d-1)+1)編碼
JAVA編碼實現spa
public static void main(String[] args) { int[][] maps = { {0, 0, 0, 0, 0, 0}, {0, 0, 0, 1, 1, 0}, {0, 0, 0, 1, 0, 1}, {0, 1, 1, 0, 0, 1}, {0, 1, 0, 0, 0, 1}, {0, 0, 1, 1, 1, 0} }; int shortDistance = shortDistance(maps, 1, 2); System.out.println("最短路徑:" + shortDistance); } public static int shortDistance(int[][] maps, int x, int y) { int min = maps[x][y]; if (min == 0) { for (int i = 1; i < maps[y].length; i++) { if (maps[x][i] == 1) { int tmp = shortDistance(maps, x, i); if (tmp + 1 < min || min == 0) { min = tmp + 1; } } } } return min; }