Java for LeetCode 051 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.

解题思路:经典的八皇后问题,由于之前在《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;
  }

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。