hdu1016(简单深搜)

这是一个简单深搜问题,要求相邻的数之间相加为素数。采用深搜,把满足条件的值放在parent[]中。最后输出parent[].

A ring is compose of n circles as shown in diagram. Put natural number 1, 2, ..., n into each circle separately, and the sum of numbers in two adjacent circles should be a prime.

Note: the number of first circle should always be 1.


 

Input
n (0 < n < 20).
 

Output
The output format is shown as sample below. Each row represents a series of circle numbers in the ring beginning from 1 clockwisely and anticlockwisely. The order of numbers must satisfy the above requirements. Print solutions in lexicographical order.

You are to write a program that completes above process.

Print a blank line after each case.
 

Sample Input
  
  
6 8
 

Sample Output
  
  
Case 1: 1 4 3 2 5 6 1 6 5 2 3 4 Case 2: 1 2 3 8 5 6 7 4 1 2 5 8 3 4 7 6 1 4 7 6 5 8 3 2 1 6 7 4 3 8 5 2
实现代码:
import java.util.Scanner;

public class Main {
	static int k=0;
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while (sc.hasNext()) {
			int n = sc.nextInt();  //输入个数
			int[] a = new int[n];  //用来装(1~n)
			int[] color = new int[n]; //用来做标记
			int[] parent = new int[n]; //用来装结果的数组
			int count = 0;   //用来记录搜索个数
			System.out.println("Case "+(++k)+":");
			// 初始化数据
			for (int i = 0; i < n; i++) {
				a[i] = i + 1;
				color[i] = -1;//把未搜索的标记为-1
				parent[i] = -1;
			}
			dfs(a, color, parent, 0, count);
			System.out.println();
		}
	}

	private static void dfs(int[] a, int[] color, int[] parent, int u, int count) {
		color[u] = 1; //把搜索过的标记为1
		count++;
		//递归跳出的条件:次数到达了给定的的个数即数组a[]的长度;最后一个数和第一个数相加满足是素数
		if (count == a.length && isPrime(a[u] + a[0])) {
			parent[count - 1] = a[u];//把最后一个结果放到parent中
			print(parent);//输出结果
			return;
		}
		for (int v = 0; v < a.length; v++) {
			//满足color值为-1和当前值和下一个值相加为素数进入dfs
			if (color[v] == -1 && isPrime(a[v] + a[u])) {
				parent[count - 1] = a[u];//把满足的值放在结果数组中
				dfs(a, color, parent, v, count);
				color[v] = -1;//还原标记
			}
		}
	}
    //输出结果
	private static void print(int[] parent) {
		for (int i = 0; i < parent.length; i++) {
			if (i < parent.length - 1) {
				System.out.print(parent[i] + " ");
			} else {
				System.out.println(parent[i]);
			}
		}
	}

	//判断是否为素数
	private static boolean isPrime(int num) {
		for (int i = 2; i * i <= num; i++) {
			if (num % i == 0) {
				return false;
			}
		}
		return true;
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值