LeetCode—n-queens(n皇后問題)—java

題目描述

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;
    }
}



發佈了146 篇原創文章 · 獲贊 13 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章