zoukankan      html  css  js  c++  java
  • 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;
      }
    
  • 相关阅读:
    Mac下安装svn服务器
    php 当前日期加一天和指定日期加一天
    MariaDB与MySQL
    JS中判断null、undefined与NaN的方法
    PHP保留两位小数的几种方法
    jquery的cookie插件
    mysql(5.7以上)查询报错:ORDER BY clause is not in GROUP BY..this is incompatible with sql_mode=only_full_group_by
    MySQL数据的导出和导入
    qrCode二维码字符串长度太多压缩的问题
    解决 img 标签上下出现的间隙
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4505145.html
Copyright © 2011-2022 走看看