Depth-first search and breadth-first search Java implementation based on graphs

Source: Internet
Author: User
Tags int size prev

To understand the 15puzzle problem, take a look at depth first search and breadth first search. First to discuss depth first search (DFS), the goal of depth first is to first search the farthest from the starting vertex of those paths, and breadth-first search is the first to search the distance from the beginning of the nearest path. I think about the difference between depth-first search and backtracking. Baidu, said backtracking is a deep search, the difference is that backtracking does not preserve the search tree. What about breadth-first search (BFS) and what are its applications? Answer: The shortest path, the issue of alcohol, eight digital issues. To come to the point, here I use Java simple to achieve a wide search and deep search. Deep search is to use the figure + stack to achieve, wide search using figure + queue implementation, the code is as follows:

1. Create a new class nodirectiongraph that represents the "No to graph"

Package com.wly.algorithmbase.datastructure; /** * @author wly * */public class Nodirectiongraph {private int mmaxsize;//The maximum number of vertices contained in the figure private Graphvertex [] vertexlist; Vertex array private int[][] indicatormat; An adjacency matrix, private int Nvertex, indicating the connectivity between vertices;
		The number of vertices currently actually saved is public nodirectiongraph (int maxSize) {mmaxsize = maxSize;
		Vertexlist = new Graphvertex[mmaxsize];
		Indicatormat = new Int[mmaxsize][mmaxsize];
		Nvertex = 0;
			Initializes the adjacency matrix element to 0 for (int j=0;j<mmaxsize;j++) {for (int k=0;k<mmaxsize;k++) {Indicatormat[j][k] = 0;
			
		}} public void Addvertex (Graphvertex v) {if (Nvertex < mmaxsize) {vertexlist[nvertex++] = V;
		else {System.out.println ("---insert failed, vertex number reached upper limit!"); }/** * Modifies the adjacency matrix, adds a new edge * @param start * @param end/public void Addedge (int start,int end) {Indicatormat [Start]
		[end] = 1;
	Indicatormat[end][start] = 1; /** * Print adjacency Matrix * */public void Printindicatormat () {for (int[) line:indicatormat) {for (int i:line) {System.out.print (i + "");
		} System.out.println (); }/** * Depth First traversal * @param vertexindex represents the starting point to traverse, that is, the number of rows in the adjacency matrix of the graph/public void DFS (int vertexindex) {Arraystack s
		Tack = new Arraystack ();
		1. Add the retrieved element to the stack vertexlist[vertexindex].setvisited (true);
		Stack.push (Vertexindex);
		int nextvertexindex = Getnextvertexindex (Vertexindex); while (!stack.isempty ()) {//constantly pressing the stack, out of the stack, until the stack is empty (retrieving elements also did not pop up the stack) if (Nextvertexindex!=-1) {vertexlist[nextvertexindex].se
				Tvisited (TRUE);
				Stack.push (Nextvertexindex);
			Stack.printelems ();
			else {stack.pop (); 
			///Retrieves whether the current stack top element contains other skipped nodes if (!stack.isempty ()) {Nextvertexindex = Getnextvertexindex (Stack.peek ()); /** * Gets the next vertex of the current vertex row * @param column * @return/public int getnextvertexindex (int column) {for ( int i=0;i<indicatormat[column].length;i++) {if (indicatormat[column][i] = = 1 &&!vertexlist[i].isvisited ()
			) {return i; }} Return-1; /** * Breadth-First traversal * @param vertexindex represents the starting point to traverse, that is, the number of rows in the adjacency matrix of the graph */public void BFS (int vertexindex) {Chainqueue Queu
		E = new Chainqueue ();
		Vertexlist[vertexindex].setvisited (TRUE);
		Queue.insert (New Queuenode (Vertexindex));
		int nextvertexindex = Getnextvertexindex (Vertexindex);
				while (!queue.isempty ()) {if (Nextvertexindex!=-1) {vertexlist[nextvertexindex].setvisited (true);
			Queue.insert (New Queuenode (Nextvertexindex));
			else {queue.remove ();
				} if (!queue.isempty ()) {Nextvertexindex = Getnextvertexindex (Queue.peek (). data);
			Queue.printelems (); }
		}
	}
}

2. Then a stack arraystack with an array simulation

Package com.wly.algorithmbase.datastructure; 
	/** * uses array to implement stack structure * @author wly * * */public class Arraystack {private int[] tarray; private int topindex =-1; Represents the index position of the current top element of the stack private int capacity_step = 12; 
	Array capacity expansion step public arraystack () {/*** a way to create a generic array ***/Tarray = new Int[capacity_step];
			/** * Pop-up Stack top element method * @return/public int pop () {if (IsEmpty ()) {System.out.println ("error, element in stack is empty, cannot pop");
		return-1;
			else {int i = Tarray[topindex]; tarray[topindex--] =-1;
		Erase pop element return I;
			}/** * Inserts an element into the stack * @param t/public void push (int t) {//check stack is full if (TopIndex = = (tarray.length-1)) {
			Extended capacity int[] Temparray = new Int[tarray.length + capacity_step];
			for (int i=0;i<tarray.length;i++) {Temparray[i] = Tarray[i];
			} Tarray = Temparray;
		Temparray = null;
			else {topindex + +;
		Tarray[topindex] = t; }/** * Gets the top element of the stack, but does not eject * @return * * public int peek () {if (IsEmpty ()) {System.out.println ("error, the element in the stack is empty, cannot peek");
		return-1;
		else {return tarray[topindex];
	}/** * Determines whether the current stack is empty * @return/public Boolean isempty () {return (TopIndex < 0);  /** * The elements in the print stack/public void Printelems () {for (int i=0;i<=topindex;i++) {System.out.print (Tarray[i] + "
		");
	} System.out.println ();
 }
}
3. In a linked list simulation of the queue Chainqueue

Package com.wly.algorithmbase.datastructure; /** * Use linked list implementation Queue * * @author wly * */public class Chainqueue {private Queuenode head;//point to Queue header node private Queuenod e tail; Point to queue tail node private int size = 0; Queue Size Public chainqueue () {}/** * Insert new node to queue tail */public void Insert (Queuenode node) {//It can also be written, add TAIL.P
			Rev = node if (head = = null) {head = node;
		tail = head;
			else {node.next = tail; Tail.prev = node;
		Bidirectional connection, make sure Head.prev is not empty tail = node;
	} size++;
			/** * Remove Queue first node/public queuenode Remove () {if (!isempty ()) {Queuenode temp = head;
			head = Head.prev;
			size--;
		return temp;
			else {System.out.println ("exception action, current queue is empty!");
		return null;
		}/** * Queue is empty * * @return/public Boolean isempty () {if (Size > 0) {return false;
		else {return true;
		}/** * Returns the first node of the queue, but does not remove/public Queuenode peek () {if (!isempty ()) {returning head;
			else {System.out.println (); System. OUT.PRINTLN ("Exception action, current queue is empty!");
		return null;
	}/** * Returns the queue size * * @return/public int size () {return size;
		/** * The element in the print queue */public void Printelems () {Queuenode tempnode = head;
			while (Tempnode!= null) {System.out.print (Tempnode.data + "");
		Tempnode = Tempnode.prev;
	} System.out.println ();
	}/** * Node class * * @author wly * */class Queuenode {Queuenode prev;

	Queuenode Next;

	int data;
	public queuenode (int data) {this.data = data;
	public int GetData () {return data;
	public void SetData (int data) {this.data = data;
		@Override public String toString () {//TODO auto-generated Method Stub super.tostring ();
	Return data + "";
 }
}
4. Test the Test_bfs_dfs

Package com.wly.algorithmbase.search;
Import Com.wly.algorithmbase.datastructure.GraphVertex;

Import Com.wly.algorithmbase.datastructure.NoDirectionGraph; /** * Based on depth First search * @author wly * * */public class Test_bfs_dfs {public static void main (string[] args) {//initialization test
		Data nodirectiongraph graph = new Nodirectiongraph (7);
		Graph.addvertex (New Graphvertex ("A"));
		Graph.addvertex (New Graphvertex ("B"));
		Graph.addvertex (New Graphvertex ("C"));
		Graph.addvertex (New Graphvertex ("D"));
		Graph.addvertex (New Graphvertex ("E"));
		Graph.addvertex (New Graphvertex ("F"));
		Graph.addvertex (New Graphvertex ("G"));
		Graph.addedge (0, 1);
		Graph.addedge (0, 2);
		Graph.addedge (1, 3);
		Graph.addedge (1, 4);
		Graph.addedge (3, 6);
		
		Graph.addedge (2, 5);
		System.out.println ("--the adjacency matrix of the graph--");
		
		Graph.printindicatormat ();
		Test Deep Search System.out.println ("--depth first searching--"); Graph.
		
		 DFS (0);
			Graph = new Nodirectiongraph (7);
			Graph.addvertex (New Graphvertex ("A")); Graph.addvertex (New GraphVertex ("B"));
			Graph.addvertex (New Graphvertex ("C"));
			Graph.addvertex (New Graphvertex ("D"));
			Graph.addvertex (New Graphvertex ("E"));
			Graph.addvertex (New Graphvertex ("F"));
			Graph.addvertex (New Graphvertex ("G"));
			Graph.addedge (0, 1);
			Graph.addedge (0, 2);
			Graph.addedge (1, 3);
			Graph.addedge (1, 4);
			Graph.addedge (3, 6);
		Graph.addedge (2, 5);
		System.out.println ("--breadth First search--"); Graph.
		
	BFS (0); }
}

The diagram structure tested here is as follows:


The results of the operation are as follows:

--Graph adjacency Matrix--
0 1 1 0 0 0 0 1 0 0 1 1 0 0 1 0 0 0 0 1 0 0 1 0 0 0 0 1 0 1 0 0 0-------------------0-0-0-0-1 0 
>0 0 0 1 0 0 0--depth first search--0 1 0 1 3 0 1 3 6 0 1 4 0 2 0 2 
--Breadth First search-
5 0 
0 1 2 1 2 1 2 3 1 2 3 4 2 3 4 2 3 4 5 3 4 5 3 4 5 6 4 5 6 5- 
6 

Here need to explain the above deep search and extensive search of the results of the operation, which 0,1,2,3 ... respectively corresponding to the a,b,c,d ... A little around the Ah, forgive me ~ ~

o ~ ~ ~ ~

Reprint please retain the Source: http://blog.csdn.net/u011638883/article/details/17169071

Thank you!!


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.