八皇后问题

7 篇文章 0 订阅
public class Main {
		int queen[] = new int[8];
		int count = 0;
		
		public static void main(String[] args)
		{
			Main m = new Main();
			m.eightQueen(0);
			System.out.println(m.count);
		}
		
		/** 
		 * 测试是否满足要求,利用遍历
		 * @param x
		 * @param y
		 * @return
		 */
		public boolean checkValid(int x, int y )
		{
			int temp_x;
			int temp_y;
			for(temp_x = 0; temp_x < x; temp_x++)
			{
				temp_y = queen[temp_x];
				if(temp_y == y)
					return false;
				if(temp_y + temp_x == x + y)
					return false;
				if(temp_y - temp_x == y - x)
					return false;
			}
			return true;
		}
		/** 
		 * 回溯法求解,每次遍历,不行则向上回溯,另寻一条路
		 * @param x
		 */
		public void eightQueen(int x)
		{
			for(int y = 0; y< queen.length; y++)
			{
				if(checkValid(x, y))
				{
					if(x == 7)
					{
						count++;
						return;
					}
					queen[x] = y;
					eightQueen(x+1);
					queen[x] = 0;
				}
			}
		}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值