Classic Graph algorithm Java code Practice: Bfs,dfs and several shortest path algorithms

Source: Internet
Author: User



public class City {string name, int id;static int idcounter = 0;public City (string name) {this.name=name;id = idcounter++; }}



Import Java.util.arraylist;public class Graph {public static void main (string[] args) {//TODO auto-generated method STUBMA P M = new Map (12); City A = new City ("a"); City B = New City ("B"); City C = new City ("C"); City d = new City ("D"); City e = new City ("E"); City F = new City ("F"); City g = new City ("G"); City h = new City ("H"); City i = new City ("I"); City j = New City ("J"); City k = new City ("K"); City L = new City ("L"); M.createedge (a,b,3); M.createedge (a,c,5); M.createedge (a,d,4); M.createedge (b,f,6); M.createedge (c,d,2); M.createedge (c,g,4); M.createedge (d,e,1); M.createedge (d,h,5); M.createedge (e,f,2); M.createedge (e,i,4); M.createedge (f,j,5); M.createedge (g,h,3); M.createedge (g,k,6); M.createedge (h,i,6); M.createedge (h,k,7); M.createedge (i,j,3); M.createedge (i,l,5); M.createedge (j,l,9); M.createedge (k,l,8); System.out.println ("The graph is:\n"); System.out.println (M); System.out.println (); System.out.println ("findpathbydfs:a to K"); M.findpathbydfs (A,K); System.out.println (); System.out.println ("Findpathbybfs:a to K "); M.FINDPATHBYBFS (A,K); System.out.println (); System.out.println ("Bellmanford from A:"); M.bellmanford (a); System.out.println (); System.out.println ("Dijkstra from A:"); M.dijkstra (a); System.out.println (); System.out.println ("bellmanford,print example from A:"); M.floydwarshall (); M.printfloydwarshallforonecity (a);}}



Import Java.util.arraylist;import Java.util.linkedlist;import Java.util.queue;public class Map {double[][] A;public     Map (int n) {A = new double[n][n]; for (int i = 0;i < a.length;i++) {for (int j = 0;j < a.length;j++) {if (i = = j) a[i           ][J] = 0;           else A[i][j] =-1;        }}}arraylist<city> cities = new arraylist<city> ();p rivate double[] d;private void Relax (int u,int v) { if (D[v]>d[u]+a[v][u]) d[v]=d[u]+a[v][u];}     Private double[][] dd = null;public void Floydwarshall () {DD = new double[a.length][a.length];     int i,j,k;                 for (i = 0;i < a.length;i++) {for (j = 0;j < a.length;j++) {if (a[i][j]>0)           DD[I][J] = A[i][j];           else if (i = = j) Dd[i][j] = 0;           else dd[i][j] = 99999999;      }} for (k = 0;k < a.length;k++) for (i = 0;i < a.length;i++) for (j = 0;j < a.length;j++) { if (Dd[i][j] > DDI       [K] + dd[k][j]) {dd[i][j] = Dd[i][k] + dd[k][j]; }}}public void Printfloydwarshallforonecity (city city) {System.out.println ("Floydwarshall:"); if (DD = = null) { Floydwarshall ();} for (int i=0;i<a.length;i++) {System.out.printf ("from%s to%s shortest path is:%f\n", City.name,cities.get (i). Name, Dd[city.id][i]);}} public void Dijkstra (city city) {Dijkstra (city.id); System.out.println ("Dijkstra:"); for (int. i=0;i<a.length;i++) {System.out.printf ("from%s to%s shortest path is:%f\n ", City.name,cities.get (i). Name,d[i]);}}        public void Dijkstra (int srcid) {D = new double[a.length];            for (int i=0;i<a.length;i++) {d[i]=999999999;        } d[srcid]=0;        int[] q = new Int[a.length]; int ql=0,qf=0;        Queue for (int i=0;i<a.length;i++) q[ql++]=i;               while (QF!=QL) {int min=qf;         for (int i=qf;i<ql;i++) {if (D[q[i]]<d[q[min]]) {      Min=i;               }} int id = Q[QF];               Q[QF] = Q[min]; Q[min] = ID;               Q[QF] is the min int u=q[qf++]; for (int i=0;i<a.length;i++) {if (a[u][i]>0) {RelA                  X (U,i); }}}}public void Bellmanford (city city) {Bellmanford (city.id); System.out.println ("Bellmanford:"); for (int. i=0;i<a.length;i++) {System.out.printf ("from%s to%s shortest path is:% F\n ", City.name,cities.get (i). Name,d[i]);}} public void Bellmanford (int srcid) {D = new double[a.length];for (int i=0;i<a.length;i++) {D[i] = 99999999;//Infinity}d[ SRCID] = 0;for (int i=0;i<a.length;i++)//Outer loop number {for (int. j=0;j<a.length;j++) {for (int k=0;k<a.length;k++) {if ( a[j][k]>0) {relax (j,k);}}}} queue<integer> bfsqueue = new linkedlist<integer> () boolean[] bfsflag;int bsfpre[];p ublic void FINDPATHBYBFS (city src,city DST) {System.out.printf ("BFs Find path between '%s ' and '%s '!\n", Src.name,dst.name) Findpathbybfs (src.id, dst.id);p Rintbfs (dst.id) ;} public void Findpathbybfs (int srcid,int dstid) {bsfpre = new int[a.length];bfsqueue.clear (); bfsflag = new boolean[ a.length];for (int i=0;i<a.length;i++) {Bfsflag[i] = false;bsfpre[i] =-1;} Bfsqueue.offer (SRCID); Bfsflag[srcid] = True;while (!bfsqueue.isempty ()) {int current = Bfsqueue.poll (); for (int index=0 index<a.length;index++) {if (current = = index) continue;if (a[current][index]>0)//both are connected {if (index = = Dstid)// The target is found {Bfsflag[index] = True;bsfpre[index] = current;return;//directly returns}IF (Bfsflag[index] = = false)//Suppose not interviewed {Bfsflag[index] = True;bsfpre[index] = current;bfsqueue.offer (index);}}}} private void Printbfs (int dstid) {int index = dstid;do{system.out.printf ("<-%s", Cities.get (Index). name); index = Bsfpre[index];} while (Index! =-1); System.out.println ();} arraylist<integer> Dfspath = new arraylist<integer> (); boolean[] dfsflag;private void PrintDFS () {for (IntegEr node:dfspath) {System.out.printf ("->%s", Cities.get (node). name);} System.out.println ();} public void Findpathbydfs (city src,city DST) {System.out.printf ("Dfs find path between '%s ' and '%s '!\n", Src.name, Dst.name); Findpathbydfs (Src.id, dst.id);} public void Findpathbydfs (int srcid,int dstid) {dfspath.clear ();d fsflag = new Boolean[a.length];for (int i=0;i< a.length;i++) {Dfsflag[i] = false;} Dfspath.add (SRCID);d fsflag[srcid] = True;dfs (srcid, Dstid);p Rintdfs ();} private void Dfs (int srcid,int dstid) {for (int index=0;index<a[srcid].length;index++) {if (srcid = = index) continue;if (a[srcid][index]>0)//both connect {if (index = = dstid)//Find target {Dfsflag[index] = True;dfspath.add (index); return;} if (dfsflag[index] = = false)//Assume that the node has not interviewed {Dfsflag[index] = True;dfspath.add (index);d FS (Index,dstid); if (Dfsflag[dstid] = = false)//target not found Dfspath.remove (index); else return;}}} public void Createedge (city A, City B, double W) {a[a.id][b.id]=w; A[b.id][a.id]=w;//added by Me!cities.add (a.id,a); Cities.add (b.id,b);} Public STRing toString () {String r = "I am a map of" + A.length + "cities."; R + = "My connections are:\n"; for (int. i=0;i<a.length;i++) {for (int j=0;j<a[0].length;j++) r+=a[i][j]+ "\ T"; r+= "\ n" ;} return r;}}



Classic Graph algorithm Java code Practice: Bfs,dfs and several shortest path algorithms

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.