LeetCode—n-queens(n皇后问题)—java

138 篇文章 0 订阅
132 篇文章 0 订阅

题目描述

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 then-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.."]
]

思路解析

  • 国际象棋的皇后是可以前后左右斜上斜下移动的。
  • 首先判断给出的n是不是合法的,不合法即小于等于0时,返回空的ArrayList
  • 声明一个一维数组,下标表示行,下标对应的值表示列。这个数组用来表示皇后的位置
  • 用一个方法表示象棋中填入每一行的皇后,如果填入的行已经和n相等了,证明可以存入字符串中了,所以此时,需要有StringBuilder来每次填入,如果是皇后就append 'Q',否则是‘.’
  • 还要有一个方法判断新加入的皇后的位置是否是合法的,isValue,除了重复的情况,还要看斜着的情况。

代码

import java.util.*;
public class Solution {
    public ArrayList<String[]> solveNQueens(int n) {
        ArrayList<String[]> res = new ArrayList<String[]>();
        if(n<=0)
            return res;
        int[] columnVal = new int[n];
        DFS_helper(n,res,0,columnVal);
        return res;
    }
    public void DFS_helper(int nQueens,ArrayList<String[]> res,int row,int[] columnVal){
        if(row == nQueens){
            String[] unit = new String[nQueens];
            for(int i=0;i<nQueens;i++){
                StringBuilder s = new StringBuilder();
                for(int j=0;j<nQueens;j++){
                    if(j==columnVal[i])
                        s.append("Q");
                    else
                        s.append(".");
                }
                unit[i]=s.toString();
            }
            res.add(unit);
        }else{
            for(int i=0;i<nQueens;i++){
                columnVal[row] = i;
                if(isValid(row,columnVal))
                    DFS_helper(nQueens,res,row+1,columnVal);
            }
        }
    }
    public boolean isValid(int row,int[] columnVal){
        for(int i=0;i<row;i++){
            if(columnVal[row]==columnVal[i] || Math.abs(columnVal[row]-columnVal[i]) == row-i)
                return false;
        }
        return true;
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值