Java 八皇后

 递归解决八皇后的问题,列出所有八皇后的可能 

package com.recursion;

import java.util.Arrays;

/**
 * 	递归解决八皇后的问题
 * @author Administrator
 *
 */
public class Empress {

	// 初始化八皇后的位置
	private static int[] graph = new int [8];
	
	private static int max = 8;
	
	public static void main(String[] args) {
		check(0);
	}
	public static void check(int n) {
		
		if(n == max) {
			print();
			return;
		}
		for (int i = 0; i < graph.length; i++) {
			
			graph[n] = i;
			if(isExist(n)) {
				check(n+1);
			}
		}
	}
	
	private static void print() {
		
		System.out.println(Arrays.toString(graph));
	}
	/**
	 * 	是否可放置
	 * @param n 
	 * @return true 可以   false  不行
	 */
	public static boolean isExist(int n) {
		
		boolean isExist = true;
		for (int i = 0; i < n; i++) {
			
			if(graph[n] ==graph[i] || Math.abs(n-i) == Math.abs(graph[n] - graph[i])) {
				return false;
			}
		}
		return isExist;
	}
	
	public static void printGraph(String[][] graph) {
		
		for (String[] strings : graph) {
			Arrays.stream(strings).forEach((x)-> System.out.print(x+" "));
			System.out.println();
		}
	}
	public static String[][] createGraph(int x, int y) {
		
		String[][] graph = new String[x][y];
		
		for (int i = 0; i < x; i++) {
			
			for (int j = 0; j < y; j++) {
				graph[i][j] = "口";
			}
		}
		return graph;
	}
	
	
}

  注意:代码还未经过测试,借鉴时请注意, 抄的韩顺平老师的数据结构分析

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java八皇后问题是一个经典的回溯算法问题,目标是在一个8x8的棋盘上放置8个皇后,使得它们互相之间不能攻击到对方。在这个问题中,皇后可以攻击同一行、同一列以及同一对角线上的其他皇后。 递归是解决八皇后问题的常用方法之一。下面是一个简单的Java代码示例: ```java public class EightQueens { private static final int SIZE = 8; private static int[] queens = new int[SIZE]; public static void main(String[] args) { solve(0); } private static void solve(int row) { if (row == SIZE) { printQueens(); return; } for (int col = 0; col < SIZE; col++) { if (isValid(row, col)) { queens[row] = col; solve(row + 1); } } } private static boolean isValid(int row, int col) { for (int i = 0; i < row; i++) { if (queens[i] == col || queens[i] - col == i - row || queens[i] - col == row - i) { return false; } } return true; } private static void printQueens() { for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { if (queens[i] == j) { System.out.print("Q "); } else { System.out.print(". "); } } System.out.println(); } System.out.println(); } } ``` 在这段代码中,我们使用一个一维数组`queens`来表示每一行皇后所在的列数。`solve`方法是递归的核心部分,它尝试在当前行的每一列放置皇后,并递归地调用下一行。`isValid`方法用于判断当前位置是否可以放置皇后,它检查同一列、同一对角线上是否已经存在皇后。当放置完最后一行的皇后时,我们就找到了一个解,通过`printQueens`方法打印出棋盘。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值