Depth-First search (DFS) and breadth-first search (BFS) for graphs

Source: Internet
Author: User

1, Depth first

Get away from the starting point ASAP

Crying to find the farthest node (therefore, "depth first" can be understood as "far priority")

1. First access a neighbor from the starting point

2. With this neighbor as a springboard, all of this neighbor's neighbors are visited (of course, in the neighbor's neighbors, the neighbor's neighbor will be visited to complete, the end result is the neighbor back, in fact, all have been visited)

3.2 When finished, go back to the starting point and then access the starting point of the next neighbor

From here in 1, 2, 3 can be clearly seen "away from the starting point, try to access the farthest node"


2. Breadth First

The process of expanding the water ripple (close to your own before all Access )
Once you have accessed all the nodes that are close to you, you will not find the outer layer until you finish.

As close as possible to the starting point


To tell you the truth, it's actually quite simple.

University was so bitter, 100% or because there was no one to fear the slightest of the programming foundation. The slightest programming experience is not, but also to see the complex of a hair C + + code, do not know the big classroom inside is not a classmate really understand. May also have NB Brothers understand, anyway, with my IQ can not do ah.

Fortunately, this time to fill it up, right when it is children's books, really not difficult

Well, put the code paste, right when you make a record, a total of four files:

Vertex.java

/** * Describe The vertex in the graph * * */public
class Vertex {
	private Object carryinginfo;
	Private Boolean wasvisited;

	Public Object Getcarryinginfo () {
		return carryinginfo;
	}

	public void Setcarryinginfo (Object carryinginfo) {
		this.carryinginfo = carryinginfo;
	}

	public Boolean iswasvisited () {
		return wasvisited;
	}

	public void setwasvisited (Boolean wasvisited) {
		this.wasvisited = wasvisited;
	}

	Public Vertex (Object carryinginfo) {
		this.carryinginfo = carryinginfo;
		wasvisited = false;
	}

	@Override public
	String toString () {
		return carryinginfo.tostring ();
	}

}


Graph.java

public class Graph {/** * The maximal permitted count of vertices.

	The real vertices count is * <code>nVerts</code> */public static final int max_vertex = 20;
	 /** * Matrix used to store the relationship among vertices. 
	* * Some tailing rows and columns may be empty, the effective Row/column * Count <code>nVerts</code> * *
	Public int[][] Adjmat = new Int[max_vertex][max_vertex]; /** * Array used to store each vertex * * The effective counts of this Array is <code>nVerts</code> *

	/Public vertex[] arrayvertices = new Vertex[max_vertex];

	/** * Real vertices count */public int nverts;
		Public Graph () {nverts = 0; for (int row = 0, row < Max_vertex; row++) {for (int column = 0; column < Max_vertex; column++) {Adjmat[row
			][column] = 0;
		}}} public void Addvertex (Object carryinginfo) {Vertex v = new Vertex (carryinginfo);
		Arrayvertices[nverts] = v;
	nverts++; } public void Addedge(int start, int end)
		{Adjmat[start][end] = 1;
	Adjmat[end][start] = 1;
		} public void Removeedge (int start, int end) {Adjmat[start][end] = 0;
	Adjmat[end][start] = 0;
	} public void Displayvertex (Vertex v) {System.out.println (V.getcarryinginfo ());
 }
}


Searchgraph.java

Import java.util.ArrayList;
Import Java.util.Iterator;
Import java.util.LinkedList;
Import java.util.List;
Import Java.util.Queue;

Import Java.util.Stack; public class Searchgraph {public static list<object> Dfs (Graph g) {list<object> Listaccessorder = new ARR
		Aylist<object> ();

		Elements in it had already been visited stack<vertex> Stack = new stack<vertex> ();
		Vertex Startvertex = Pickfirstaccessvertex (g);
		Stack.push (Startvertex);
		Startvertex.setwasvisited (TRUE);
		Listaccessorder.add (Startvertex.getcarryinginfo ());

		System.out.println ("Push into stack:" + Startvertex); while (!stack.empty ()) {Vertex Topvertex = Stack.peek ();//This had already been visited. We//Peek It (not pop), and find one//unvisited neighbour of it (Some//Neighbours had
											Already been//visited, but the other had not. So, we ' re going to find one of//the unvisited Neighbours)//Find Its next unvisted neighbour Vertex Unvisitedneighbour = Findoneunvisitedneighbour (g, Topvertex); Yes, we find a vertex of this kind if (unvisitedneighbour! = null) {Stack.push (unvisitedneighbour);//(Of Cours E, this new pushed//one is the next peeked//vertex) unvisitedneighbour.setwasvisited (true)
				;
				Listaccessorder.add (Unvisitedneighbour.getcarryinginfo ());
			System.out.println ("Push into stack:" + unvisitedneighbour);
				}//No, no this kind of neighbour else {System.out.println ("stack Status just before POPs:" + stack); Stack.pop ();//Topvertex (it's on the top of the stack). When POPs, we//cannot find any neighbours which had not been//visited (all neighbours of this vertex had a
	Lready//Been visited)}} return listaccessorder;

		} public static list<object> BFS (Graph g) {list<object> Listaccessorder = new arraylist<object> (); queue<vertex> queue = new LInkedlist<vertex> ();
		Vertex Startvertex = Pickfirstaccessvertex (g);
		Queue.offer (Startvertex);
		Startvertex.setwasvisited (TRUE);
		Listaccessorder.add (Startvertex.getcarryinginfo ());

		SYSTEM.OUT.PRINTLN ("Offer for Queue:" + Startvertex);
			while (!queue.isempty ()) {System.out.println ("queue status just before poll:" + queue);
												Vertex Headvertex = Queue.poll ();//This had already been visited.
												When poll a vertex, this//polled one had already been//visited, and NONE of its Neighbours//except that one who introduce//it into the queue have been//visit

			ed list<vertex> listallremainingunvisitedneighbour = Findallremainingunvisitedneighbour (g, HeadVertex); Yes, we find all remaining vertices of this kind if (listallremainingunvisitedneighbour.size () > 0) {for ( iterator<vertex> it = listallremainingunvisitedneighbour. Iterator (); It. Hasnext ();)
					{Vertex Oneneighbour = (Vertex) it.next (); Queue.offer (Oneneighbour);//When to offer into the queue, this one//had already been visited, but//I TS neighbours except//<code>headVertex</code> has//not been visited yet Onen
					Eighbour.setwasvisited (TRUE);
					Listaccessorder.add (Oneneighbour.getcarryinginfo ());
				SYSTEM.OUT.PRINTLN ("Offer for Queue:" + oneneighbour);
	}}//No, no this kind of neighbour else {}} return listaccessorder;
	} private static Vertex Pickfirstaccessvertex (Graph g) {return g.arrayvertices[0];
		} private static Vertex Findoneunvisitedneighbour (Graph g, Vertex v) {int row =-1;
				for (int i = 0; i < g.nverts; i++) {if (g.arrayvertices[i] = = v) {row = i;
			Break }} if (Row < 0) {return null;//never happen} for (int column = 0; column < g.nverts; column++) {/ /Not only neighbour of V, but also not beEn visited if (g.adjmat[row][column] = = 1 && g.arrayvertices[column].iswasvisited () = = False) {return
			G.arrayvertices[column];
	}} return null; } private static List<vertex> Findallremainingunvisitedneighbour (Graph g, Vertex v) {list<vertex> List
		Allunvisitedneighbour = new arraylist<vertex> ();
		int row =-1;
				for (int i = 0; i < g.nverts; i++) {if (g.arrayvertices[i] = = v) {row = i;
			Break }} if (Row < 0) {return listallunvisitedneighbour;//never happen} for (int column = 0; column < G.nve RTs column++) {//Not only neighbour of V, but also not been visited if (g.adjmat[row][column] = = 1 && g.a
			rrayvertices[column].iswasvisited () = = False) {Listallunvisitedneighbour.add (G.arrayvertices[column]);
	}} return listallunvisitedneighbour;
 }
}


Main.java

Import java.util.List;

public class Main {public
	static Graph createtestgraph () {
		graph G = new Graph ();
		G.addvertex ("A");
		G.addvertex ("B");
		G.addvertex ("C");
		G.addvertex ("D");
		G.addvertex ("E");
		G.addvertex ("F");
		G.addvertex ("G");
		G.addvertex ("H");
		G.addvertex ("I");

		G.addedge (0, 1);//A--b
		G.addedge (0, 2);//a--c
		G.addedge (0, 3);//a--d
		G.addedge (0, 4);//A--e
		G.addedge (1, 5);//B--f
		G.addedge (5, 7);//F--h
		G.addedge (3, 6);//D--g
		G.addedge (6, 8);//G--i
		return g;
	}

	public static void Main (string[] args) {
		System.out.println ("Begin dfs Search");
		List Dfsaccessorder = Searchgraph.dfs (Createtestgraph ());
		System.out.println ("dfs:" + dfsaccessorder);

		System.out.println ("Begin BFS Search");
		List Bsfaccessorder = Searchgraph.bfs (Createtestgraph ());
		System.out.println ("BFS:" + Bsfaccessorder);
	}
}

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.