zoukankan      html  css  js  c++  java
  • N-Queens

    Link: http://oj.leetcode.com/problems/n-queens/

    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     
     3     public  ArrayList<String[]> result = new ArrayList<String[]>();
     4 
     5     public  ArrayList<String[]> solveNQueens(int n) {
     6         if (n < 1)
     7             return null;
     8         result = new ArrayList<String[]>();
     9         int[] queens = new int[n + 1];
    10         for (int i = 1; i <= n; i++) {
    11             queens[1] = i;
    12             dfs(2, n, queens);
    13         }
    14         return result;
    15     }
    16 
    17     public  void dfs(int row, int size, int[] queens) {
    18         if (row > size) {
    19             print_queen(size,queens);
    20             return;
    21         }
    22         for (int i = 1; i <= size; i++) {
    23             if (isValid(row, i, queens)) {
    24                 queens[row] = i;
    25                 dfs(row + 1, size, queens);
    26                 queens[row] = 0;
    27 
    28             }
    29         }
    30     }
    31 
    32     public  boolean isValid(int row, int col, int[] queens) {
    33         for (int i = 1; i < row; i++) {
    34             if (queens[i] != 0
    35                     && (queens[i] == col || (Math.abs(i - row) == Math
    36                             .abs(queens[i] - col)))) {
    37                 return false;
    38             }
    39         }
    40 
    41         return true;
    42     }
    43         public  void print_queen(int size,int[] queens) {
    44         String[] str = new String[size];
    45         for (int i = 1; i <=size; i++) {
    46             int temp = queens[i];
    47             String s = "";
    48             for (int j = 0; j < size; j++) {
    49                 if (j + 1 == temp) {
    50                     s += "Q";
    51                     continue;
    52                 }
    53                 s += ".";
    54             }
    55             str[i - 1] = s;
    56         }
    57         result.add(str);
    58     }
    59 }
  • 相关阅读:
    Linux 操作文件目录
    前端HTML所遇到的报错
    【剑指offer】最小的k个数
    【剑指offer】数组中出现次数超过一半的数字
    【剑指offer】栈的压入、弹出序列
    【剑指offer】二叉树的镜像
    【剑指offer】反转链表
    【剑指offer】数值的整数次方
    【剑指offer】重建二叉树
    【剑指offer】旋转数组的最小数字
  • 原文地址:https://www.cnblogs.com/Altaszzz/p/3715034.html
Copyright © 2011-2022 走看看