博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JAVA算法:DFS算法求解素数环问题
阅读量:4040 次
发布时间:2019-05-24

本文共 1536 字,大约阅读时间需要 5 分钟。

DFS算法求解素数环问题

问题描述

输入正整数n,把整数1,2,3,…,n组成一个环,使得相邻两个整数之和均为素数,输出从整数1开始逆时针排列。

同一个环应该只输出一次。n<=16.

问题分析

该问题可以有多种求解算法,本次使用DFS算法求解。

算法设计

package com.bean.algorithmbasic;import java.util.Arrays;import java.util.Scanner;public class PrimeCircleDemo {		/*	 * 输入正整数n,把整数1,2,3,...,n组成一个环,	 * 使得相邻两个整数之和均为素数,输出从整数1开始逆时针排列。	 * 同一个环应该只输出一次。n<=16.	 * */	public static void dfsSearch(int[] res, int[] visited, int n, int cursor) {		if (cursor == n && isPrime(res[0] + res[n - 1])) {			StringBuffer str = new StringBuffer();			for (int i : res) {				str.append(i + " ");			}			System.out.println(str.substring(0, str.length() - 1));			return;		}		for (int i = 2; i <= n; i++) {			if (visited[i - 1] == 0) {				if (cursor > 0) {					if (!isPrime(i + res[cursor - 1]))						continue;				}				res[cursor] = i;				//设置标记				visited[i - 1] = 1;				//搜索下一个位置				dfsSearch(res, visited, n, cursor + 1);				//清除标记				visited[i - 1] = 0;			}		}	}	/*	 * 判断是否为素数	 * */	public static boolean isPrime(int n) {		//如果n==1直接返回,因为1不是素数		if (n == 1)			return false;		//设置标记		boolean flag = true;		//从i=2开始,直到i的平方根为止		for (int i = 2; i <= Math.sqrt(n); i++) {			if (n % i == 0) {				flag = false;				break;			}		}		return flag;	}	public static void main(String[] args) {		Scanner scanner = new Scanner(System.in);		while (scanner.hasNext()) {			int n = scanner.nextInt();			int[] res = new int[n];			int[] visited = new int[n];			res[0] = 1;			Arrays.fill(visited, 0);			//调用搜索算法			dfsSearch(res, visited, n, 1);		}		scanner.close();	}}

输入:6

运行结果:

1 4 3 2 5 6

1 6 5 2 3 4

(完)

转载地址:http://rwtdi.baihongyu.com/

你可能感兴趣的文章
2020年终总结
查看>>
linux内核学习(4)建立正式内核的页式内存映射, 以x86 32位模式为例
查看>>
Homebrew指令集
查看>>
React Native(一):搭建开发环境、出Hello World
查看>>
React Native(二):属性、状态
查看>>
JSX使用总结
查看>>
React Native(四):布局(使用Flexbox)
查看>>
React Native(七):Android双击Back键退出应用
查看>>
Android自定义apk名称、版本号自增
查看>>
adb command not found
查看>>
Xcode 启动页面禁用和显示
查看>>
【剑指offer】q50:树中结点的最近祖先
查看>>
二叉树的非递归遍历
查看>>
【leetcode】Reorder List (python)
查看>>
【leetcode】Linked List Cycle (python)
查看>>
【leetcode】Linked List Cycle (python)
查看>>
【leetcode】Word Break(python)
查看>>
【leetcode】Candy(python)
查看>>
【leetcode】Clone Graph(python)
查看>>
【leetcode】Sum Root to leaf Numbers
查看>>