Algorithm note _071:SPFA algorithm Brief introduction (Java)

Source: Internet
Author: User

Directory

1 Problem Description

2 Solutions

2.1 Specific Code

  1 problem description

What is the spfa(shortest Path Faster algorithm) algorithm?

SPFA algorithm function: Given a weighted connected graph, select a vertex, called the starting point, to find the shortest distance from the starting point to all other vertices, the notable feature is that you can PS: reference from Baidu Encyclopedia : SPFA Bellman-ford algorithm, which reduces the redundancy of the Span style= "font-family: Arial" > relaxation operation

SPFA algorithm idea:SPFA is A way of realization of Bellmanford, the specific difference is that, for handling the relaxation operation, The queue (FIFO) operation is used, which greatly improves the complexity of time. (PS: For Bellmanford algorithm can refer to my other article algorithm note _070:bellmanford algorithm simple introduction (Java))

2 Solutions 2.1 specific code

The time complexity of SPFA algorithm for finding single source shortest path is O (m*e). (where m is the average number of all vertices entering the team, it can be shown that m is generally less than or equal to the number of vertices ,E is the edge collection of the given graph)

first look at the connected graphs used in the code ( PS: The graph is undirected connected, so there are two edges between each of the two vertices):

now take the middle vertex the shortest distance from B to all other vertices.

The specific code is as follows:

 PackageCom.liuzhen.chapter9;Importjava.util.ArrayList;ImportJava.util.Scanner; Public classSPFA { Public Long[] result;//used to get the shortest distance between the first s vertices and the other vertices//inner class for storing specific edge data of a diagram    classEdge { Public intA//the beginning of the side         Public intb//the end of the edge         Public intValue//weighted value of the edgeEdge (intAintBintvalue) {             This. A =A;  This. B =b;  This. Value =value; }    }    /** Parameter N: The number of vertices of the given graph * parameter s: the shortest distance between the first s vertex and all other vertices * parameter edge: The specific side of the given graph * Function function: If the given graph does not contain negative weight loop, then the final result can be obtained, if it contains a negative weight loop, it cannot be Get the final result*/     Public BooleanGetshortestpaths (intNints, edge[] A) {ArrayList<Integer> list =NewArraylist<integer>(); Result=New Long[n]; Boolean[] used =New Boolean[n]; int[] num =New int[n];  for(inti = 0;i < n;i++) {Result[i]=Integer.max_value; Used[i]=false; } Result[s]= 0;//the first s vertex to self distance is 0Used[s] =true;//represents the first s vertex into the array teamNum[s] = 1;//indicates that the first s vertex has been traversed onceList.add (s);//The first s vertex is enqueued         while(List.size ()! = 0) {            intA = List.get (0);//gets the first element in the array teamList.remove (0);//Delete the first element in the array team             for(inti = 0;i < a.length;i++) {                //When the first element of the list array team equals the beginning of the edge A[i]                if(A = = A[i].a && result[a[i].b] > RESULT[A[I].A] +a[i].value) {RESULT[A[I].B]= Result[a[i].a] +A[i].value; if(!used[a[i].b])                        {List.add (a[i].b); NUM[A[I].B]++; if(Num[a[i].b] >N)return false; USED[A[I].B]=true;//endpoint B representing Edge A[i] has entered the array team}}} Used[a]=false;//vertex a array pairs        }        return true; }         Public Static voidMain (string[] args) {SPFA test=NewSPFA (); Scanner in=NewScanner (system.in); System.out.println ("Please enter the total number of vertices of a graph n start subscript s and the total number of sides P:"); intn =In.nextint (); ints =In.nextint (); intp =In.nextint (); Edge[] A=NewEdge[p]; System.out.println ("Please enter data for specific edges:");  for(inti = 0;i < p;i++) {             intA =In.nextint (); intb =In.nextint (); intValue =In.nextint (); A[i]= Test.NewEdge (A, B, value); }        if(Test.getshortestpaths (n, S, A)) { for(inti = 0;i < test.result.length;i++) System.out.print (Test.result[i]+" "); } ElseSystem.out.println ("There is a negative ring in the given graph, there is no shortest distance"); }}

Operation Result:

Please enter the total number of vertices of a graph n start subscript s and the total number of sides P:6 1 Please enter data for specific edges:

Resources:

1. SPFA Algorithm Detailed

Algorithm note _071:SPFA algorithm Brief introduction (Java)

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.