N-Queens 1&2

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.."]
]
solution:经典八皇后问题(这里是n),用递归算法解决
ps:
国际象棋中,皇后会攻击横行竖行和斜线的位置的棋子。楼主用的二维数组比较直观。
package leetcode2;
import java.util.*;
public class N_QUEEN {
    public static ArrayList<String[]> Nqueen(int n){
        ArrayList<String[]> res=new ArrayList<String[]>();
        char[][] location=new  char[n][n];
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                location[i][j]='.';
            }
        }
        int count=0;
        Queens(res,n,0,count,location);
        System.out.print("\t"+res.size()+"  \n");
        return res;
        
    }
    public static void Queens(ArrayList<String[]> res,int n,int deep,int count,char[][] location1){
          if(n==0){
            String[] sub=new String[location1.length];
            for(int i=0;i<location1.length;i++){
             sub[i]=new String(location1[i]);    
             System.out.print("   "+sub[i]);
            }
            res.add(sub);            
            count++;
        //    System.out.print(count);
            return;
        }
        for(int y=0;y<location1.length;y++) {
        if(isvaild(deep,y,location1)){
            location1[y][deep]='Q';
            Queens(res,n-1,deep+1,count,location1);
            location1[y][deep]='.';
        }
        
        }
        
    }
    
    public static boolean isvaild(int y, int x,char[][] location) {
        // TODO Auto-generated method stub
        boolean flag=true;
       for(int i = 0; i < location.length; i++) {
                if(location[i][y] == 'Q' || location[x][i] == 'Q') return false; 
            }
            //left diagonal
            for(int i = x, j = y; i >=0 && j>=0; j--, i--)
                if(location[i][j] == 'Q') return false; 
            for(int i = x, j = y; i <location.length && j>=0; j--, i++)
                if(location[i][j] == 'Q') return false; 
            return true;    
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
      System.out.println(Nqueen(4));
    }

}

 




posted @ 2015-04-06 12:27  微微程序媛  阅读(152)  评论(0编辑  收藏  举报