Problem Description
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.
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.
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
这也算是一个深搜的例子的,我的代码可能有点超内存,主要是在输出语句中要改下,这个就看你们自己了,仅供参考:
主要是要学会那种深搜的思想
1. 深度优先搜索思想
深度优先搜索遍历类似于树的先序遍历。假定给定图G的初态是所有顶点均未被访问过,在G中任选一个顶点i作为遍历的初始点,则深度优先搜索递归调用包含以下操作:
(1)访问搜索到的未被访问的邻接点;
(2)将此顶点的visited数组元素值置1;
(3)搜索该顶点的未被访问的邻接点,若该邻接点存在,则从此邻接点开始进行同样的访问和搜索。
深度优先搜索DFS可描述为:
(1)访问v0顶点;
(2)置 visited[v0]=1;
(3)搜索v0未被访问的邻接点w,若存在邻接点w,则DFS(w)。
遍历过程:
DFS 在访问图中某一起始顶点 v 后,由 v 出发,访问它的任一邻接顶点 w1;再从 w1 出发,访问与 w1邻 接但还没有访问过的顶点 w2;然后再从 w2 出发,进行类似的访问,… 如此进行下去,直至到达所有的邻接顶点都被访问过的顶点 u 为止。
接着,退回一步,退到前一次刚访问过的顶点,看是否还有其它没有被访问的邻接顶点。如果有,则访问此顶点,之后再从此顶点出发,进行与前述类似的访问;如果没有,就再退回一步进行搜索。重复上述过程,直到连通图中所有顶点都被访问过为止。
package search;
import java.util.Scanner;
public class SearchMathodDFS1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int n = sc.nextInt();
int a[] = new int[n];// 定义一个数组来放 数字
int color[] = new int[n];// 定义一个颜色数组用来标记颜色;
int parent[] = new int[n];// 用来记录父节点
for (int i = 0; i < a.length; i++) {
a[i] = i + 1;
color[i] = -1;
parent[i] = -1;
}
int count = 0;// 计数
int starNumber = 0;
dfs(a, color, parent, starNumber, count);
}
}
private static void dfs(int[] a, int[] color, int[] parent, int u, int count) {
count++;
color[u] = 1;// 改變顏色
// 递归鸿沟
if (count == a.length && isPrime(a[0] + a[u])) {
parent[0] = u;
print(a, parent);// 输出
return;
}
for (int v = 1; v < a.length; v++) {
if (color[v] == -1 && isPrime(a[u] + a[v])) {
parent[v] = u;
dfs(a, color, parent, v, count);
// ※※还原现场
color[v] = -1;
parent[v] = -1;
}
}
}
private static void print(int[] a, int[] parent) {
int index[] = new int[parent.length];
int p = 0;
for (int i = 0; i < parent.length; i++) {
index[parent.length - 1 - i] = parent[p];
p = parent[p];
}
for (int i = 0; i < index.length; i++) {
if (i < index.length - 1) {
System.out.print(a[index[i]] + " ");
} else {
System.out.println(a[index[i]]);
}
}
}
// 判斷素數
private static boolean isPrime(int n) {
if (n == 2) {
return true;
}
for (int i = 2; i <= n / 2; i++) {
if (n % i == 0)
return false;
}
return true;
}
}