zoukankan      html  css  js  c++  java
  • Java for LeetCode 052 N-Queens II

    Follow up for N-Queens problem.

    Now, instead outputting board configurations, return the total number of distinct solutions.

    解题思路:和上题一样《JAVA语言程序设计》中exerice6-22已经给出了计算count的代码,直接拿来用即可,JAVA实现如下:

    static public int totalNQueens(int n) {
    	 if(n==1)
    		 return 1;
    	 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++;  
    	        else {
    	          k++;
    	        }
    	      }
    	    }
         return count; 
      }
      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;
      }
    
  • 相关阅读:
    MyBatis之启动分析(一)
    通俗算法教程03
    数学倒底有没有绝对的严格性和形式化?
    通俗算法教程02
    .NET Core 中正确使用 HttpClient 的姿势
    通俗算法教程01
    我要写一篇文章吗?
    [ASP.NET MVC 小牛之路]18
    [ASP.NET MVC 小牛之路]17
    [ASP.NET MVC 小牛之路]16
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4505161.html
Copyright © 2011-2022 走看看