Chinaunix首页 | 论坛 | 博客
  • 博客访问: 74063
  • 博文数量: 16
  • 博客积分: 31
  • 博客等级: 民兵
  • 技术积分: 187
  • 用 户 组: 普通用户
  • 注册时间: 2010-11-19 19:58
个人简介

一步一个阶梯,向人类进化。

文章分类

全部博文(16)

文章存档

2018年(1)

2015年(3)

2014年(11)

2013年(1)

我的朋友

分类: Java

2015-01-07 16:55:56


The n-queens puzzle is the problem of placing n queens on an n×n 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行到第n行遍历,每次保证不会被前面的皇后杀到,如果能遍历到最后一行,就代表当前的解法可行。这里需要设置一个n长的标志数组,存放皇后所在的位置,用于检测后面放置的皇后是否会被杀到。从下图可以看到,这种解法的时间复杂度不高。

Java代码:

点击(此处)折叠或打开

  1. public class Solution{
  2.     public List<String[]> solveNQueens(int n) {
  3.         int []flag = new int[n];
  4.         for(int i = 0; i < n; i ++){
  5.             flag[i] = -1;
  6.         }
  7.         List<String[]> result = new ArrayList<String[]>();
  8.         for(int i = 0; i < n; i ++){
  9.             flag[0] = i;
  10.             queens(n, 1, flag, result);
  11.         }
  12.         return result;
  13.     }
  14.     public void queens(int n, int curRow, int []flag, List<String[]> result)
  15.     {
  16.         if(curRow == n){
  17.             String []solution = new String[n];
  18.             for(int i = 0; i < n; i ++){
  19.                 String rowSol = "";
  20.                 for(int j = 0;j < n; j ++){
  21.                     if(flag[i] != j){
  22.                         rowSol += '.';
  23.                     }else{
  24.                         rowSol += 'Q';
  25.                     }
  26.                 }
  27.                 solution[i] = rowSol;
  28.             }
  29.             result.add(solution);
  30.             return;
  31.         }
  32.         for(int i = 0; i < n; i ++){
  33.             int j = 0;
  34.             for(; j < curRow;j++){
  35.                 if((i == flag[j]) || (i == flag[j] + (curRow - j)) || (i == flag[j] - (curRow - j))){
  36.                     break;
  37.                 }
  38.             }
  39.             if(j == curRow){
  40.                 flag[curRow] = i;
  41.                 queens(n, curRow + 1, flag, result);
  42.             }
  43.         }
  44.     }
  45. }


阅读(1897) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~