回溯法——八皇后问题 n-queens

题目描述


一个8*8的棋盘上有八个皇后,使她们互相不能攻击(即两个皇后不能出现在同一行,同一列,或同一对角线上)。

package TraceBack;

public class 八皇后问题 {
	public static void main(String[] args) {
		// TODO 自动生成的方法存根
           int []data={0,1,2,3,4,5,6,7};//用一个数组存放0-7则行列必然不会相等,只考虑对角情况即可;
           int []count=new int[1];//用来存放满足情况的个数  92.
           八皇后问题 test=new 八皇后问题();
           test.permutation(data, 0,count);
           System.out.println(count[0]+"");  
	}
	public void permutation(int[] data,int index,int[] count)
    {
   	 if(index==data.length-1)
   	 {
   		 boolean flag=true;
   		for(int i=0;i<8;i++)
   		{
   			for(int j=i+1;j<8;j++)
   			{
   				if(Math.abs(data[i]-data[j])==Math.abs(i-j))
   				{
   					flag=false;
   					break;
   				}
   			}
   		}
   		if(flag==true)
   		{
   			count[0]++;
   		}
   	 }
   	 for(int i=index;i<data.length;i++)
   	 {
   			 swap(data,index,i);
   			 permutation(data,index+1,count);
   			 swap(data,index,i);
   	 }
    }
    public void swap(int []data,int index,int i)
    {
   	int temp=data[index];
   	data[index]=data[i];
   	data[i]=temp;
    }
 }


n-queens

题目描述

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens' placement, where'Q'and'.'both indicate a queen and an empty space respectively.

For example,
There exist two distinct solutions to the 4-queens puzzle:

[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]

将皇后的位置作为字符数组存储下来,代码如下:
import java.util.*;
public class Solution { 
    public ArrayList<String[]> solveNQueens(int n) {
        ArrayList<String[]> array=new ArrayList();
        if(n < 1)
            return array;
        int[] num=new int[n];//仍用数字数组模拟的方法
        for(int i=0;i<n;i++)
            num[i]=i;
        perm(num,0,array);
        return array;
    }
    public void perm(int[] num,int start,ArrayList<String[]> array)
        {
        if(start == num.length-1)
            {
            boolean flag=false;
            for(int i=0;i<num.length-1;i++)
                {
                for(int j=i+1;j<num.length;j++)
                    {
                    if(Math.abs(num[i]-num[j]) == Math.abs(i-j))//判断是否不能互相攻击
                        {
                        flag=true;
                        break;
                    }
                }
            }
            if(flag == false)//若满足要求,则构建字符串数字,并保存下来
                {
                String[] strs=new String[num.length];
                for(int i=0;i<num.length;i++)
                    {
                    StringBuilder sb=new StringBuilder();
                    for(int j=0;j<num.length;j++)
                        sb.append('.');
                    sb.setCharAt(num[i],'Q');
                    strs[i]=sb.toString();
                }
                array.add(strs);
                return;
            }
        }
        for(int i=start;i<num.length;i++)
            {
            swap(num,start,i);
            perm(num,start+1,array);
            swap(num,start,i);
        }
    }
    public void swap(int[] num,int i,int j)
        {
        int temp=num[i];
        num[i]=num[j];
        num[j]=temp;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
八皇后问题是一个经典的回溯问题,以下是求解该问题的代码: ```python class EightQueens: def __init__(self, n): self.n = n # 棋盘大小 self.solution = [-1] * n # 解法数组 def is_valid(self, row, col): # 判断当前位置是否合法 for i in range(row): # 判断同一列是否有皇后 if self.solution[i] == col: return False # 判断对角线是否有皇后 if abs(i - row) == abs(self.solution[i] - col): return False return True def backtrack(self, row): # 找到解法 if row == self.n: print(self.solution) return # 遍历每一列 for col in range(self.n): # 判断当前位置是否合法 if self.is_valid(row, col): self.solution[row] = col # 继续寻找下一行的解法 self.backtrack(row + 1) # 回溯 self.solution[row] = -1 def solve(self): self.backtrack(0) if __name__ == '__main__': n = 8 eight_queens = EightQueens(n) eight_queens.solve() ``` 在这个代码中,我们定义了一个 EightQueens 类,其中包含了 is_valid 和 backtrack 两个函数。is_valid 函数用来判断当前位置是否合法,backtrack 函数用来回溯求解八皇后问题。 在主函数中,我们创建了一个 EightQueens 对象,然后调用了 solve 函数来求解八皇后问题。求解过程中,我们遍历每一行,对于每一行,我们遍历每一列,判断当前位置是否合法,如果合法,就将皇后放置在该位置,然后继续寻找下一行的解法。如果找到了解法,就输出解法。如果没有找到解法,就回溯到上一行,重新寻找解法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值