leetcode -- N-Queens

The n-queens puzzle is the problem of placing n queens on an nn 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 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.."]

]
 1 public class Solution {

 2     public static void main(String[] args) {

 3         ArrayList<String[]> result = solveNQueens(4);

 4         System.out.println(result.size());

 5         for(int i = 0; i < result.size(); i++){

 6             System.out.println("solution:" + i);

 7             for(int j = 0; j < result.get(i).length; j++){

 8                 System.out.println(result.get(i)[j]);

 9             }

10         }

11     }

12 

13     public static ArrayList<String[]> solveNQueens(int n) {

14         // Start typing your Java solution below

15         // DO NOT write main() function

16         ArrayList<String[]> result = new ArrayList<String[]>();

17         int depth = 0;

18         int[] rows = new int[n];

19         for (int i = 0; i < n; i++) {

20             rows[i] = n + 1;

21         }

22         dfs(depth, rows, n, result);

23         return result;

24     }

25 

26     public static void dfs(int depth, int[] rows, int n, ArrayList<String[]> result) {

27         if (depth == n) {

28             String[] s = new String[n];

29             for (int i = 0; i < n; i++) {

30                 int m = rows[i];

31                 StringBuilder tmp = new StringBuilder();

32                 for (int j = 0; j < n; j++) {

33                     if (j == m) {

34                         tmp.append("Q");

35                         continue;

36                     }

37                     tmp.append(".");

38                 }

39                 s[i] = tmp.toString();

40             }

41             result.add(s);

42             return;

43         }

44         for (int i = 0; i < n; i++) {

45             rows[depth] = i;

46             if (isValid(rows, depth)) {

47                 dfs(depth + 1, rows, n, result);

48             }

49         }

50 

51     }

52     public static boolean isValid(int[] rows, int depth) {

53         for (int i = 0; i < depth; i++) {

54             if (rows[i] == rows[depth]

55                     || Math.abs(rows[i] - rows[depth]) == Math.abs(i - depth)) {

56                 return false;

57             }

58         }

59         return true;

60     }

61 }

 

你可能感兴趣的:(LeetCode)