图论算法(一)--最短路径的DFS/BFS解法(JAVA )
生活随笔
收集整理的這篇文章主要介紹了
图论算法(一)--最短路径的DFS/BFS解法(JAVA )
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
最短路徑–城市路徑問(wèn)題:
問(wèn)題描述:求從1號(hào)城市到5號(hào)城市的最短路徑長(zhǎng)度
Input:
5 8
1 2 2
1 5 10
2 3 3
2 5 7
3 1 4
3 4 4
4 5 5
5 3 3
Output:
9
DFS
import java.util.Scanner; public class minPath {static int min = 99999999;static int[][] e = new int[100][100];static int[] book = new int[100];static int n, m;static Scanner input = new Scanner(System.in);public static void main(String[] args) {n = input.nextInt();m = input.nextInt();for (int i = 1; i <= n; i++) {for (int j = 1; j <= m; j++) {if (i == j) {e[i][j] = 0;} else {e[i][j] = 99999999;}}}for (int i = 1; i <= m; i++) {int a = input.nextInt();int b = input.nextInt();int c = input.nextInt();e[a][b] = c;}book[1] = 1;dfs(1, 0);System.out.println(min);}public static void dfs(int cur, int dis) {/*** 如果當(dāng)前路徑大于之前找到的最小值,可直接返回* */if (dis > min) {return;}/*** 判斷是否達(dá)到最后一個(gè)結(jié)點(diǎn),更新最小值,返回* */if(cur == n) {if (dis < min) {min = dis;return;}}/*** 當(dāng)前點(diǎn)到其他各點(diǎn)之間可連通但是還未添加進(jìn)來(lái)時(shí),遍歷執(zhí)行* */for (int i = 1; i <= n; i++) {if (e[cur][i] != 99999999 && book[i] == 0) {book[i] = 1;dfs(i, dis+e[cur][i]);/*** 回溯**/book[i] = 0;}}return;} }最短路徑–轉(zhuǎn)乘問(wèn)題:
問(wèn)題描述:求從1號(hào)城市到5號(hào)城市的最短路徑長(zhǎng)度
Input:
5 7 1 5
1 2
1 3
2 3
2 4
3 4
3 5
4 5
Output:
2
這個(gè)題目與上一個(gè)的區(qū)別就在于,這些路徑是沒(méi)有權(quán)值的,也就是說(shuō)只需要找出到達(dá)一個(gè)點(diǎn)的最短距離就可以了,記錄次數(shù)即可。
BFS
import java.util.LinkedList; import java.util.Queue; import java.util.Scanner;class node {int x;int s;node(int x, int s) {this.x = x;this.s = s;} }public class minPath {static int[][] e = new int[51][51];static int[] book = new int[51];static int n, m;static int start, end;static int mark, sum;static Queue<node> queue = new LinkedList<>();static Scanner input = new Scanner(System.in);public static void main(String[] args) {n = input.nextInt();m = input.nextInt();start = input.nextInt();end = input.nextInt();for (int i = 1; i <= n; i++) {for (int j = 0; j <= m; j++) {if (i == j) {e[i][j] = 0;} else {e[i][j] = 99999999;}}}for (int i = 1; i <= m; i++) {int a = input.nextInt();int b = input.nextInt();e[a][b] = 1;e[b][a] = 1;}queue.offer(new node(start, 0));book[1] = start;bfs();System.out.println(sum);}public static void bfs() {int flag = 0;while (!queue.isEmpty()) {int cur = queue.peek().x;for (int i = 1; i <= n; i++) {if(e[cur][i] != 99999999 && book[i] == 0) {mark = i;sum = queue.peek().s + 1;queue.offer(new node(i, sum));book[i] = 1;}if(mark == end) {flag = 1;break;}}if(flag == 1) {break;}queue.remove();}return;} }基本上能用深度優(yōu)先的問(wèn)題都可以用廣度優(yōu)先,但是廣度優(yōu)先更適合無(wú)向圖,或者說(shuō)所有邊的權(quán)值一樣的情況,大家可以通過(guò)多做題靈活使用這兩種方法
總結(jié)
以上是生活随笔為你收集整理的图论算法(一)--最短路径的DFS/BFS解法(JAVA )的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Mysql的高可用方案及主从详细配置
- 下一篇: 图论算法(六)-- 二分图的最大分配问题