这是一个简单深搜问题,要求相邻的数之间相加为素数。采用深搜,把满足条件的值放在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; } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-23 03:08:56