【LeetCode】N-Queens && 【九度】题目1140:八皇后

N-Queens 
Total Accepted: 3171 Total Submissions: 12620 My Submissions
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

【LeetCode】N-Queens && 【九度】题目1140:八皇后_第1张图片

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.."]
]
著名的N皇后问题,经典的DFS,我发现BFS也可以过。BFS比DFS慢了140ms。
和九度题目1140:八皇后解法一致。

Java DFS AC

public class Solution {
    public ArrayList<String[]> solveNQueens(int n) {
        list = new ArrayList<String[]>();
        if(n <= 0){
            return list;
        }
        int []queen = new int[n + 1];
        for(int i = 1; i < n+1 ; i++){
            queen[1] = i;
            dfs(queen,2,n);
        }
        return list;
    }
    public ArrayList<String[]> list;
    public void dfs(int queen[], int line, int n) {
        if(line == n+1){
            String[] tempArr = new String[n];
            for(int i = 1; i < n+1; i++){
            	StringBuffer sb = new StringBuffer();
            	for (int j = 1; j < n+1; j++) {
					if (queen[i] == j) {
						sb.append("Q");
					}else {
						sb.append(".");
					}
				}
            	tempArr[i-1] = sb.toString();
            }
            list.add(tempArr);
            return;
        }
        for(int i = 1; i < n+1; i++){
            if(valid(line, i, queen)){
                queen[line] = i;
                dfs(queen ,line+1, n);
                queen[line] = 0;
            }
        }
    }
    public boolean valid(int row, int col, int []queen) {
        for (int i = 1; i < row; i++) {
            if (queen[i] != 0 && (queen[i] == col
				|| Math.abs(i - row) == Math.abs(queen[i] - col)))  
                return false;  
        }
        return true;
    }
}
Java BFS AC

public class Solution {
    public ArrayList<String[]> solveNQueens(int n) {
        ArrayList<String[]> list = new ArrayList<String[]>();
        if(n <= 0){
            return list;
        }
        for(int i = 1; i < n+1; i++){
            Queue<Node> queue = new LinkedList<Node>();
            String[][] queenArr = new String[n+1][n+1];
            queenArr[1][i] = "Q";
            int location[] = new int[n+1];
            location[1] = i;
            queue.offer(new Node(location,queenArr,1));
            bfs(list,queue,n);
        }
        return list;
    }
    public void bfs(ArrayList<String[]> list,Queue<Node> queue, int n){
        
        while(!queue.isEmpty()){
            Node node = queue.peek();
            queue.poll();
            String [][]tempArr = node.queenArr;
            int location[] = node.location;
            int line = node.line;
            if(line == n){
                String array[] = new String[n];
                for(int i = 1; i < n+1 ; i++){
                    StringBuffer sb = new StringBuffer();
                    for(int j = 1; j < n+1; j++){
                        if(tempArr[i][j] == null){
                            tempArr[i][j] = ".";
                        }
                        sb.append(tempArr[i][j]);
                    }
                    array[i-1] = sb.toString();
                }
                list.add(array);
                continue;
            }
            for(int i = 1; i < n+1; i++){
            	String array[][] = new String[n+1][n+1];
            	int queen[] = new int[n+1];
                if(valid(line+1,i,location,n)){
                    for (int j = 1; j < n+1; j++) {
						queen[j] = location[j];
					}
                    queen[line+1] = i;
                    for (int j = 1; j < n+1; j++) {
						for (int k = 1; k < n+1; k++) {
							array[j][k] = tempArr[j][k];
						}
					}
            		array[line+1][i] = "Q";
                    queue.offer(new Node(queen,array,line+1));
                }
            }
        }
    }
    
    public boolean valid(int row, int col, int queen[], int n ) {
        for (int i = 1; i < row; i++) {
            if (queen[i] != 0 && (queen[i] == col 
				|| Math.abs(i - row) == Math.abs(queen[i] - col))){
            	return false;
            }
        }
        return true;
    }
    public class Node{
        int location[];
        String[][] queenArr;
        int line;
        Node(int location[], String [][]queenArr, int line){
            this.location = location;
            this.queenArr = queenArr;
            this.line = line;
        }
    }
}
九度题目1140:八皇后 Java AC

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.util.ArrayList;
import java.util.Collections;
 
public class Main{
    /*
     * 1140
     */
    public static void main(String[] args) throws Exception {
        int n = 8;
//      count = 0;
        solveNQueens(n);
        StreamTokenizer st = new StreamTokenizer
				(new BufferedReader(new InputStreamReader(System.in)));
        while (st.nextToken() != StreamTokenizer.TT_EOF) {
            int allNum = (int) st.nval;
            while (allNum > 0) {
                st.nextToken() ;
                int seq = (int) st.nval;
//              Collections.sort(arrList);
//              System.out.println(count);
                System.out.println(list.get(seq-1));
                allNum -- ;
            }
        }
    }
    public static void solveNQueens(int n) {
        list = new ArrayList<String>();
        if(n <= 0){
            return;
        }
        int []queen = new int[n + 1];
        for(int i = 1; i < n+1 ; i++){
            queen[1] = i;
            dfs(queen,2,n);
        }
        Collections.sort(list);
    }
    public static ArrayList<String> list;
    public static void dfs(int queen[], int line, int n) {
        if(line == n+1){
            StringBuffer sb = new StringBuffer();
            for(int i = 1; i < n+1; i++){
                sb.append(queen[i]);
            }
            list.add(sb.toString());
            return;
        }
        for(int i = 1; i < n+1; i++){
            if(valid(line, i, queen)){
                int array[] = new int[n+1];
                for(int j = 1; j < n+1; j++){
                    array[j] = queen[j];
                }
                array[line] = i;
                dfs(array ,line+1, n);
            }
        }
    }
    public static boolean valid(int row, int col, int []queen) {
        for (int i = 1; i < row; i++) {
            if (queen[i] != 0 && (queen[i] == col 
				|| Math.abs(i - row) == Math.abs(queen[i] - col)))  
                return false;  
        }
        return true;
    }
}
/**************************************************************
    Problem: 1140
    User: wangzhenqing
    Language: Java
    Result: Accepted
    Time:130 ms
    Memory:21604 kb
****************************************************************/


你可能感兴趣的:(【LeetCode】N-Queens && 【九度】题目1140:八皇后)