Day 34-35

Day 34

一、学习内容

深度优先遍历:选择一个起点开始访问,下一个访问起点的邻接点,重复以上步骤,指导没有邻接点之后原路返回,再按上述规则访问未被访问的节点。和广度优先遍历不同的是一条道走到黑

访问顺序:v1-v2-v4-v8-v5-v3-v6-v7

v1-v2-v5-v8-v4-v3-v7-v6

代码中测试的无向图:

深度访问顺序:0-1-3-2

package datastructure.graph;
import datastructure.queue.CircleObjectQueue;

import matrix.IntMatrix;
 
import datastructure.stack.ObjectStack;

/**
 * Directed graph. Note that undirected graphs are a special case of directed
 * graphs.
 * 
 * @author Fan Min minfanphd@163.com.
 */
public class Graph {
 
	/**
	 * The connectivity matrix.
	 */
	IntMatrix connectivityMatrix;
 
	/**
	 *********************
	 * The first constructor.
	 * 
	 * @param paraNumNodes
	 *            The number of nodes in the graph.
	 *********************
	 */
	public Graph(int paraNumNodes) {
		connectivityMatrix = new IntMatrix(paraNumNodes, paraNumNodes);
	}// Of the first constructor
 
	/**
	 *********************
	 * The second constructor.
	 * 
	 * @param paraMatrix
	 *            The data matrix.
	 *********************
	 */
	public Graph(int[][] paraMatrix) {
		connectivityMatrix = new IntMatrix(paraMatrix);
	}// Of the second constructor
 
	/**
	 *********************
	 * Overrides the method claimed in Object, the superclass of any class.
	 *********************
	 */
	public String toString() {
		String resultString = "This is the connectivity matrix of the graph.\r\n"
				+ connectivityMatrix;
		return resultString;
	}// Of toString
 
	/**
	 *********************
	 * Get the connectivity of the graph.
	 * 
	 * @throws Exception
	 *             for internal error.
	 *********************
	 */
	public boolean getConnectivity() throws Exception {
		// Step 1. Initialize accumulated matrix: M_a = I.
		IntMatrix tempConnectivityMatrix = IntMatrix
				.getIdentityMatrix(connectivityMatrix.getData().length);
 
		// Step 2. Initialize M^1.
		IntMatrix tempMultipliedMatrix = new IntMatrix(connectivityMatrix);
 
		// Step 3. Determine the actual connectivity.
		for (int i = 0; i < connectivityMatrix.getData().length - 1; i++) {
			// M_a = M_a + M^k
			tempConnectivityMatrix.add(tempMultipliedMatrix);
 
			// M^k
			tempMultipliedMatrix = IntMatrix.multiply(tempMultipliedMatrix, connectivityMatrix);
		} // Of for i
 
		// Step 4. Check the connectivity.
		System.out.println("The connectivity matrix is: " + tempConnectivityMatrix);
		int[][] tempData = tempConnectivityMatrix.getData();
		for (int i = 0; i < tempData.length; i++) {
			for (int j = 0; j < tempData.length; j++) {
				if (tempData[i][j] == 0) {
					System.out.println("Node " + i + " cannot reach " + j);
					return false;
				} // Of if
			} // Of for j
		} // Of for i
 
		return true;
	}// Of getConnectivity
 
	/**
	 *********************
	 * Unit test for getConnectivity.
	 *********************
	 */
	public static void getConnectivityTest() {
		// Test an undirected graph.
		int[][] tempMatrix = { { 0, 1, 0 }, { 1, 0, 1 }, { 0, 1, 0 } };
		Graph tempGraph2 = new Graph(tempMatrix);
		System.out.println(tempGraph2);
 
		boolean tempConnected = false;
		try {
			tempConnected = tempGraph2.getConnectivity();
		} catch (Exception ee) {
			System.out.println(ee);
		} // Of try.
 
		System.out.println("Is the graph connected? " + tempConnected);
 
		// Test a directed graph.
		// Remove one arc to form a directed graph.
		tempGraph2.connectivityMatrix.setValue(1, 0, 0);
 
		tempConnected = false;
		try {
			tempConnected = tempGraph2.getConnectivity();
		} catch (Exception ee) {
			System.out.println(ee);
		} // Of try.
 
		System.out.println("Is the graph connected? " + tempConnected);
	}// Of getConnectivityTest
 
 
	/**
	 *********************
	 * Breadth first traversal.
	 * 
	 * @param paraStartIndex The start index.
	 * @return The sequence of the visit.
	 *********************
	 */
	public String breadthFirstTraversal(int paraStartIndex) {
		CircleObjectQueue tempQueue = new CircleObjectQueue();
		String resultString = "";
		
		int tempNumNodes = connectivityMatrix.getRows();
		boolean[] tempVisitedArray = new boolean[tempNumNodes];
		
		tempVisitedArray[paraStartIndex] = true;
		
		//Initialize the queue.
		//Visit before enqueue.
		tempVisitedArray[paraStartIndex] = true;
		resultString += paraStartIndex;
		tempQueue.enqueue(new Integer(paraStartIndex));
		
		//Now visit the rest of the graph.
		int tempIndex;
		Integer tempInteger = (Integer)tempQueue.dequeue();
		while (tempInteger != null) {
			tempIndex = tempInteger.intValue();
					
			//Enqueue all its unvisited neighbors.
			for (int i = 0; i < tempNumNodes; i ++) {
				if (tempVisitedArray[i]) {
					continue; //Already visited.
				}//Of if
				
				if (connectivityMatrix.getData()[tempIndex][i] == 0) {
					continue; //Not directly connected.
				}//Of if
				
				//Visit before enqueue.
				tempVisitedArray[i] = true;
				resultString += i;
				tempQueue.enqueue(new Integer(i));
			}//Of for i
			
			//Take out one from the head.
			tempInteger = (Integer)tempQueue.dequeue();
		}//Of while
		
		return resultString;
	}//Of breadthFirstTraversal
	
	/**
	 *********************
	 * Unit test for breadthFirstTraversal.
	 *********************
	 */
	public static void breadthFirstTraversalTest() {
		// Test an undirected graph.
		int[][] tempMatrix = { { 0, 1, 1, 0 }, { 1, 0, 0, 1 }, { 1, 0, 0, 1}, { 0, 1, 1, 0} };
		Graph tempGraph = new Graph(tempMatrix);
		System.out.println(tempGraph);
 
		String tempSequence = "";
		try {
			tempSequence = tempGraph.breadthFirstTraversal(2);
		} catch (Exception ee) {
			System.out.println(ee);
		} // Of try.
 
		System.out.println("The breadth first order of visit: " + tempSequence);
	}//Of breadthFirstTraversalTest
 
	/**
	 *********************
	 * The entrance of the program.
	 * 
	 * @param args
	 *            Not used now.
	 *********************
	 */
	/**
	 *********************
	 * Depth first traversal.
	 * 
	 * @param paraStartIndex The start index.
	 * @return The sequence of the visit.
	 *********************
	 */
	public String depthFirstTraversal(int paraStartIndex) {
		ObjectStack tempStack = new ObjectStack();
		String resultString = "";
		
		int tempNumNodes = connectivityMatrix.getRows();
		boolean[] tempVisitedArray = new boolean[tempNumNodes];
		
		//Initialize the stack.
		//Visit before push.
		tempVisitedArray[paraStartIndex] = true;
		resultString += paraStartIndex;
		tempStack.push(new Integer(paraStartIndex));
		System.out.println("Push " + paraStartIndex);
		System.out.println("Visited " + resultString);
		
		//Now visit the rest of the graph.
		int tempIndex = paraStartIndex;
		int tempNext;
		Integer tempInteger;
		while (true){
		//Find an unvisited neighbor.
			tempNext = -1;
			for (int i = 0; i < tempNumNodes; i ++) {
				if (tempVisitedArray[i]) {
					continue; //Already visited.
				}//Of if
				
				if (connectivityMatrix.getData()[tempIndex][i] == 0) {
					continue; //Not directly connected.
				}//Of if
				
				//Visit this one.
				tempVisitedArray[i] = true;
				resultString += i;
				tempStack.push(new Integer(i));
				System.out.println("Push " + i);
				tempNext = i;
				
				//One is enough.
				break;
			}//Of for i
			
			
			if (tempNext == -1) {
				//No unvisited neighbor. Backtracking to the last one stored in the stack.
				//Attention: This is the terminate condition!
				if (tempStack.isEmpty()) {
					break;
				}//Of if
				tempInteger = (Integer)tempStack.pop();
				System.out.println("Pop " + tempInteger);
				tempIndex = tempInteger.intValue();
			} else {
				tempIndex = tempNext;
			}//Of if
		}//Of while
		
		return resultString;
	}//Of depthFirstTraversal
	
	/**
	 *********************
	 * Unit test for depthFirstTraversal.
	 *********************
	 */
	public static void depthFirstTraversalTest() {
		// Test an undirected graph.
		int[][] tempMatrix = { { 0, 1, 1, 0 }, { 1, 0, 0, 1 }, { 1, 0, 0, 0}, { 0, 1, 0, 0} };
		Graph tempGraph = new Graph(tempMatrix);
		System.out.println(tempGraph);

		String tempSequence = "";
		try {
			tempSequence = tempGraph.depthFirstTraversal(0);
		} catch (Exception ee) {
			System.out.println(ee);
		} // Of try.

		System.out.println("The depth first order of visit: " + tempSequence);
	}//Of depthFirstTraversalTest

	/**
	 *********************
	 * The entrance of the program.
	 * 
	 * @param args
	 *            Not used now.
	 *********************
	 */
	public static void main(String args[]) {
		System.out.println("Hello!");
		Graph tempGraph = new Graph(3);
		System.out.println(tempGraph);

		// Unit test.
		getConnectivityTest();
		
		breadthFirstTraversalTest();

		depthFirstTraversalTest();
	}// Of main

}
 

 二、实现结果

 

Day 35

一、学习内容:

       回溯法简单来说就是按照深度优先的顺序,穷举所有可能性的算法,回溯算法可以随时判断当前状态是否符合问题的条件。一旦不符合条件,那么就退回到上一个状态,省去了继续往下探索的时间。

回溯法简介:理解回溯算法——回溯算法的初学者指南_Hello World-CSDN博客_回朔算法

求序列[1,2,3]的全排列,可以画出一颗解空间树。

解空间树


	/**
	 *********************
	 * Coloring. Output all possible schemes.
	 * 
	 * @param paraNumColors The number of colors.
	 *********************
	 */
	public void coloring(int paraNumColors) {
		// Step 1. Initialize.
		int tempNumNodes = connectivityMatrix.getRows();
		int[] tempColorScheme = new int[tempNumNodes];
		Arrays.fill(tempColorScheme, -1);

		coloring(paraNumColors, 0, tempColorScheme);
	}// Of coloring

	/**
	 *********************
	 * Coloring. Output all possible approaches.
	 * 
	 * @param paraNumColors The number of colors.
	 * @return The sequence of the visit.
	 *********************
	 */
	public void coloring(int paraNumColors, int paraCurrentNumNodes, int[] paraCurrentColoring) {
		// Step 1. Initialize.
		int tempNumNodes = connectivityMatrix.getRows();

		System.out.println("coloring: paraNumColors = " + paraNumColors + ", paraCurrentNumNodes = "
				+ paraCurrentNumNodes + ", paraCurrentColoring" + Arrays.toString(paraCurrentColoring));
		// A complete scheme.
		if (paraCurrentNumNodes >= tempNumNodes) {
			System.out.println("Find one:" + Arrays.toString(paraCurrentColoring));
			return;
		} // Of if

		// Try all possible colors.
		for (int i = 0; i < paraNumColors; i++) {
			paraCurrentColoring[paraCurrentNumNodes] = i;
			if (!colorConflict(paraCurrentNumNodes + 1, paraCurrentColoring)) {
				coloring(paraNumColors, paraCurrentNumNodes + 1, paraCurrentColoring);
			} // Of if
		} // Of for i
	}// Of coloring

	/**
	 *********************
	 * Coloring conflict or not. Only compare the current last node with previous
	 * ones.
	 * 
	 * @param paraCurrentNumNodes The current number of nodes.
	 * @param paraColoring        The current coloring scheme.
	 * @return Conflict or not.
	 *********************
	 */
	public boolean colorConflict(int paraCurrentNumNodes, int[] paraColoring) {
		for (int i = 0; i < paraCurrentNumNodes - 1; i++) {
			// No direct connection.
			if (connectivityMatrix.getValue(paraCurrentNumNodes - 1, i) == 0) {
				continue;
			} // Of if

			if (paraColoring[paraCurrentNumNodes - 1] == paraColoring[i]) {
				return true;
			} // Of if
		} // Of for i
		return false;
	}// Of colorConflict

	/**
	 *********************
	 * Coloring test.
	 *********************
	 */
	public static void coloringTest() {
		int[][] tempMatrix = { { 0, 1, 1, 0 }, { 1, 0, 0, 1 }, { 1, 0, 0, 0 }, { 0, 1, 0, 0 } };
		Graph tempGraph = new Graph(tempMatrix);
		//tempGraph.coloring(2);
		tempGraph.coloring(3);
	}// Of coloringTest

	/**
	 *********************
	 * The entrance of the program.
	 * 
	 * @param args Not used now.
	 *********************
	 */
	public static void main(String args[]) {
		System.out.println("Hello!");
		Graph tempGraph = new Graph(3);
		System.out.println(tempGraph);

		// Unit test.
		getConnectivityTest();

		breadthFirstTraversalTest();

		depthFirstTraversalTest();

		coloringTest();
	}// Of main

二、实现结果 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值