码迷,mamicode.com
首页 > 编程语言 > 详细

Java for LeetCode 051 N-Queens

时间:2015-05-15 10:32:24      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

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.

解题思路:经典的八皇后问题,由于之前在《JAVA语言程序设计》中exerice6-22中做过这种问题,代码直接拿来修改下即可,JAVA实现如下:

static public List<String[]> solveNQueens(int n) {
	 List<String[]> list=new ArrayList<String[]>();
	 if(n==1){
		 String[] str={"Q"};
		 list.add(str);
		 return list;
	 }
//	 int count = 0; 
	    int[] queens = new int[n]; // queens are placed at (i, queens[i])
	    for (int i = 0; i < n; i++)
	      queens[i] = -1; 
	    queens[0] = 0; 
	    int k = 1;
	    while (k >=0) {
	      int j = findPosition(k, queens,n);
	      if (j ==-1) {
	        queens[k] = -1;
	        k--; // back track to the previous row
	      } else {
	        queens[k] = j;
	        if (k == n-1) {
//	          count++; 
	          String[] queenArray=new String[n];
	          for(int i=0;i<n;i++){
	        	  StringBuilder sb=new StringBuilder();
	        	  for(int j2=0;j2<n;j2++){
	        		  if(j2==queens[i])
	        			  sb.append(‘Q‘);
	        		  else sb.append(‘.‘);
	        	  }
	        	  queenArray[i]=new String(sb);
	          }
	          list.add(queenArray);
	        } 
	        else {
	          k++;
	        }
	      }
	    }
     return list; 
  }
  public static int findPosition(int k, int[] queens,int n) {
    int start = queens[k] == -1 ? 0 : queens[k] + 1;
    for (int j = start; j < n; j++) {
      if (isValid(k, j, queens,n))
        return j; 
    }
    return -1;
  }

  public static boolean isValid(int k, int j, int queens[],int n) {
    for (int i = 0; i < k; i++)
      if (queens[i] == j)
        return false;
    for (int row = k - 1, column = j - 1; row >= 0 && column >= 0; row--, column--)
      if (queens[row] == column)
        return false;
    for (int row = k - 1, column = j + 1; row >= 0 && column <= n-1; row--, column++)
      if (queens[row] == column)
        return false;
    return true;
  }

 

Java for LeetCode 051 N-Queens

标签:

原文地址:http://www.cnblogs.com/tonyluis/p/4505145.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!