藍橋杯-基礎練習-2n皇后(Java)

跟n皇后是一樣的思路,不過每行要放兩個棋子。黑皇后和白皇后的棋子分開存儲就行了。

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main{
    private static int n;
    private static List<int[]> blacks = new ArrayList<>();
    private static List<int[]> whites = new ArrayList<>();
    private static int ans;
    private static int[][] map;

    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        n = scanner.nextInt();
        map = new int[n][n];
        for(int i = 0; i < n; i++){
            for(int j = 0; j < n; j++){
                map[i][j] = scanner.nextInt();
            }
        }
        scanner.close();

        dfs(0);
        System.out.println(ans);
    }

    private static boolean isValid(int r, int c, List<int[]> queues){
        if(map[r][c] == 0) return false;

        for(int[] queue : queues){
            int qr = queue[0];
            int qc = queue[1];
            if(qc == c) return false;
            if(r - qr == Math.abs(c - qc)) return false;
        }

        return true;
    }

    private static void dfs(int row){
        if(row == n){
            ans += 1;
            return;
        }

        for(int black = 0; black < n; black++){
            if(!isValid(row, black, blacks))
                continue;

            for(int white = 0; white < n; white++){

                if(black == white)
                    continue;

                if(!isValid(row, white, whites))
                    continue;

                int[] blackQueue = new int[]{row, black};
                int[] whiteQueue = new int[]{row, white};
                blacks.add(blackQueue);
                whites.add(whiteQueue);

                dfs(row + 1);

                blacks.remove(blackQueue);
                whites.remove(whiteQueue);
            }
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章