本文主要是介绍题目1254:N皇后问题,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目1254:N皇后问题import java.io.BufferedInputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;public class Main {public static void main(String[] args){Scanner cin = new Scanner(new BufferedInputStream(System.in)) ;PrintWriter cout = new PrintWriter(System.out) ; int[] dp = new int[14] ;for(int i = 3 ; i <= 13 ; i++) dp[i] = new Task().solve(i) ;while(cin.hasNext()){cout.println( dp[cin.nextInt()] ) ;// cout.flush() ;}cout.flush() ; }}class Task{boolean[][] used ;int n ;int solve(int n){this.n = n ;used = new boolean[n][n] ;for(int i = 0 ; i < n ; i++) Arrays.fill(used[i] , false) ;return dfs(0) ;}int dfs(int row){if(row == n) return 1 ;int sum = 0 ;for(int col = 0 ; col < n ; col++){if(valid(row , col)){used[row][col] = true ;sum += dfs(row+1) ;used[row][col] = false ;}}return sum ;}boolean valid(int row , int col){for(int r = 0 ; r < row ; r++){if(used[r][col]) return false ;} int x = row , y = col ;while(x >= 0 && y >= 0){if(used[x][y]) return false ;x-- ;y-- ;}x = row ; y = col ;while(x >= 0 && y < n){if(used[x][y]) return false ;x-- ;y++ ;}return true ;}}
这篇关于题目1254:N皇后问题的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!