八皇后深搜LinkedList()实现

八皇后问题:

package tests;

import java.util.LinkedList;

import tests.Ok.Location;

public class EightQuee {
	/*
	 * 知识点:
	 * 1.深搜思想,每次从x+1行、0列开始深搜,先保证行不重复,然后判断列;
	 * 2.LinkedList<Location>list=new LinkedList<>();
	 * 3.生成一个LinkedList类、Location类型对象;
	 * 4.list.offer()、list.add()都是往里加一个元素;
	 * 5.list.pollLast(),删除末位元素;
     * 6.可以模拟队列,先进先出;
	 */
	private static final int SIZE = 8; // 皇后的个数,此处设为8,表示8个皇后

	private static int count = 0; // 记录摆放的方式数

	public static void main(String[] args) {
		LinkedList<Location> list = new LinkedList<>();
		EightQuees(list, 0, 0);// 0列0行;
		System.out.println("八皇后共有"+count+"种摆放方式");
	}

	public static void EightQuees(LinkedList<Location> list, int x, int y) {
		if (list.size() == SIZE) {
			printQueen(list);
			return;
		}
		for (int i = y; i <SIZE; i++) {
			Location loc = new Location(x, i);
			if (isLegal(list, loc)) {
				list.add(loc);
				EightQuees(list, x+1, 0);//继续从0列开始;
				list.pollLast();
			}
		}

	}

	private static boolean isLegal(LinkedList<Location> list, Location loc) {
		for (Location each : list) {
			if (loc.x == each.x || loc.y == each.y) // 判断是否在同一行或同一列
				return false;
			else if (Math.abs(loc.x - each.x) == Math.abs(loc.y - each.y)) // 判断是否在同一对角线或反对角线上
				return false;
		}
		return true;
	}


	public static void printQueen(LinkedList<Location> list) {
		++count;
		for (Location each : list) {
			System.out.print(each.toString());
		}
		System.out.println();

	}

	public static class Location {
		int x;
		int y;

		public Location(int x, int y) {
			this.x = x;
			this.y = y;
		}

		public Location() {
			x = 0;
			y = 0;
		}

		public String toString() {
			return "(" + x + "," + y + ") ";
		}
	}

}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值