day35

本文介绍了回溯法的概念,将其比喻为解题时的试错过程,并详细阐述了如何运用回溯法解决图的着色问题。通过一个具体的例子展示了无向图的着色需求,解释了如何确保相邻节点颜色不同。此外,还提供了代码实现,包括图的联通性检查、广度优先遍历和深度优先遍历。最后,探讨了图的着色算法并给出了测试用例。
摘要由CSDN通过智能技术生成

Day 35

1. Background

历经两天,我终于把图的着色问题给弄懂了。

着色问题的核心是回溯法,这个我在学习C语言的时候学过,不过那个时候我看的C语言教程是把它放到递归后面的,毕竟回溯法确实是需要用到递归嘛。大概是三年前学的,当时回溯法就一直没弄懂,后来为了进度直接放弃了回溯法的学习。没想到现在学java的时候又看到了。

2. Description

2.1 回溯法

回溯法不是什么神奇的新物种,大家应该有过这样的经历:以前在做数学题的时候,遇到一道不懂的题目,就会自然地将题目的条件代入到所有你觉得跟这道题有关联的公式中,尝试几次之后终究能找到合适的解题方法。

回溯法就是类似这样,它的指导思想是一条路走到黑,碰壁了再回来找到另一条路接着走到黑。

以上来自我当时学习C语言回溯法时教程上面所写内容。

所以,在我的心中回溯法就是一个试错的思想,一条路不通就再返回上一步,直到符合要求。

这里说一句题外话,我当时写C语言回溯法的第一想法就是用goto语句,因为返回之前的语句正好就是goto的特点。当然最后还是失败了,goto到了最后反而把自己代码的逻辑弄的混乱不堪。

2.1 图的着色问题

所谓图的着色问题,就是给定无向连通图G和m种不同的颜色。用这些颜色为图G的各顶点着色,每个顶点着一种颜色,是否有一种着色法使G中任意相邻的2个顶点着不同颜色

我们拿老师的测试数据为例子。 { { 0, 1, 1, 0 }, { 1, 0, 0, 1 }, { 1, 0, 0, 0 }, { 0, 1, 0, 0 } }矩阵如下。
t e m p M a t r i x = [ 0 1 1 0 1 0 0 1 1 0 0 0 0 1 0 0 ] tempMatrix = \begin{bmatrix} 0 & 1 & 1 & 0 \\ 1 & 0 & 0 & 1 \\ 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ \end{bmatrix} tempMatrix=0110100110000100
矩阵中可以看到,和第0个节点相连的是第1和第2个节点。所以第0个节点的颜色不能和第1、第2个一样。

然后测试数据中给定的颜色有三个,所以第0个节点的颜色有三种情况,这也就是程序中的循环。

最后,当确定了第0个节点的颜色之后,就再确定剩下的节点的颜色。确定的方法就是试错,一旦发现不符合条件,就回到上一步。这也就是回溯法。

3. Code

package datastructure.graph;

import matrix.IntMatrix;
import datastructure.CircleObjectQueue;
import datastructure.ObjectStack;
import java.util.Arrays;

public class Graph {
    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 given matrix.
     ***************
     */
    public Graph(int[][] paraMatrix) {
		connectivityMatrix = new IntMatrix(paraMatrix);
	}// Of the second constructor


    /**
     ***************
     * Overrides toString.
     ***************
     */
    public String toString() {
        String resultString = "This is the connectivity matrix of the graph.\r\n" + connectivityMatrix;
        return resultString;
    } // Of toString

    /**
     ***************
     * 获取图的联通性。
     * 
     * @throws Exception
     ***************
     */
    public boolean getConnectivity() throws Exception {
		// Step 1. 初始化矩阵,得到一个单位矩阵,这个单位矩阵的长和宽与目标连接矩阵一致.
		IntMatrix tempConnectivityMatrix = IntMatrix.getIdentityMatrix(connectivityMatrix.getData().length);

		// Step 2. Initialize M^1.
		IntMatrix tempMultipliedMatrix = new IntMatrix(connectivityMatrix);

		// Step 3. 确定实际联通性。
		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() {
		// 测试一个无向图.
		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);

		// 测试这个有向图.
		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

	public String breadthFirstTraversal(int paraStartIndex) {
		CircleObjectQueue tempQueue = new CircleObjectQueue();
		String resultString = "";
		
		int tempNumNodes = connectivityMatrix.getRows();
		boolean[] tempVisitedArray = new boolean[tempNumNodes];
		
		// 深度优先遍历的开头,即对起始节点(paraStartIndex)进行处理。
		tempVisitedArray[paraStartIndex] = true;
		resultString += paraStartIndex;
		Integer tempIndexInteger = Integer.valueOf(paraStartIndex);
		tempQueue.enQueue(tempIndexInteger); // 入队起始节点.
		
		// 访问表的剩余部分。
		int tempIndex;
		Integer tempInteger = (Integer)tempQueue.deQueue();// 出队队首节点。
		while (tempInteger != null) {
			tempIndex = tempInteger.intValue();
					
			// 访问当前出队节点的所有邻居。
			for (int i = 0; i < tempNumNodes; i ++) {
				if (tempVisitedArray[i]) {
					continue; // Already visited.
				}//Of if
				
				if (connectivityMatrix.getData()[tempIndex][i] == 0) {
					continue; // 没有和当前出队节点链接.
				}//Of if
				
				// 经过上面的筛选,执行下面代码的节点均符合要求。
				tempVisitedArray[i] = true;
				resultString += i;
				Integer tempInteger2 = Integer.valueOf(i);
				tempQueue.enQueue(tempInteger2);
			}//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

	/**
	 *********************
	 * 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];
		
		// 初始化栈,并对给定的初始点进行处理,让它进栈。
		tempVisitedArray[paraStartIndex] = true;
		resultString += paraStartIndex;
		Integer tempIntegerIndex = Integer.valueOf(paraStartIndex);
		tempStack.Push(tempIntegerIndex);
		System.out.println("Push " + paraStartIndex);
		System.out.println("Visited " + resultString);
		
		// 深度优先遍历的主体,对当前栈顶元素的下家进行入栈操作。
		int tempIndex = paraStartIndex;
		int tempNext;
		Integer tempInteger;
		while (true){
		// 不断的向下挖下家。
			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;
				Integer tempInteger2 = Integer.valueOf(i);
				tempStack.Push(tempInteger2);
				System.out.println("Push " + i);
				tempNext = i;
				
				//One is enough.
				break;
			}//Of for i
			
			
			if (tempNext == -1) {
				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

	/**
	 *********************
	 * Coloring. Output all possible schemes.
	 * 
	 * @param paraNumColors The number of colors.
	 *********************
	 */
	public void coloring(int paraNumColors) {
		// 对着色进行一个预处理。
		int tempNumNodes = connectivityMatrix.getRows();
		int[] tempColorScheme = new int[tempNumNodes];
		Arrays.fill(tempColorScheme, -1); // 将当前的着色数组里面全部初始化为-1,表示尚未开始着色。

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

	/**
	 *********************
	 * override coloring. 正式的着色方法。
	 * 
	 * @param paraNumColors The number of colors.
	 * @param paraCurrentNumNodes The number of nodes that have been colored.
	 * @param paraCurrentColoring The array recording the coloring scheme.
	 *********************
	 */
	public void coloring(int paraNumColors, int paraCurrentNumNodes, int[] paraCurrentColoring) {
		// 获得需要着色的节点数。
		int tempNumNodes = connectivityMatrix.getRows();

		System.out.println("coloring: paraNumColors = " + paraNumColors + ", paraCurrentNumNodes = "
				+ paraCurrentNumNodes + ", paraCurrentColoring" + Arrays.toString(paraCurrentColoring));
		// 退出语句,表示当前情况下的着色已经完成。
		if (paraCurrentNumNodes >= tempNumNodes) {
			System.out.println("Find one:" + Arrays.toString(paraCurrentColoring));
			return;
		} // Of if

		// 着色的正式循环
		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

	/**
	 *********************
	 * 着色判定,判断传入的两个节点符不符合要求。
	 * 
	 * @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++) {
			// 传入的两个节点不相连
			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(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
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值