java implementation algorithm-n

Posted by coolex on Thu, 28 Oct 2021 04:41:55 +0200

What is queen n

Queen n is a classical algorithm problem, that is, an n × On the chessboard of N, a queen's chess piece is placed in each row. The vertical, horizontal and oblique rows of this chess piece have no other queen conflicts

As shown in the figure

thinking

Let's talk about the idea first. The backtracking method is adopted here, that is, first adopt a possibility, and then judge whether it is feasible. If it is feasible, continue to adopt the next possibility, which is a correct solution

Backtracking method (exploration and backtracking method) is an optimization search method, also known as heuristic method. It searches forward according to the optimization conditions to achieve the goal. However, when a certain step is explored and it is found that the original selection is not excellent or fails to achieve the goal, it will go back to one step and reselect. This technology of going back and going again if it fails is the backtracking method, and the point in a certain state that meets the backtracking conditions is called the "backtracking point"---- From Baidu Encyclopedia

  1. Let's make an array arr with a size of n, which represents the number of columns in each row
  2. It is expected to write an iteration, and each iteration only calculates one line of logic. At the beginning of the iteration method, the logic that jumps out should be written, which should be when the number of cycles reaches n. or the number of lines reaches the last line
  3. After the jump method is written, write the main logic. Here, go through each column, and then try to put the queen in this column, that is, in the array arr, and then judge the compliance. The compliance will recursively judge the next row, and the non-compliance will judge the next column
  4. The method to judge compliance is to compare the queen identified in the array arr above with the current queen

code

package com.zgd.demo.suanfa.exam;

/**
 * NQueen
 *
 * @author zgd
 * @date 2021/10/28 09:41
 */
public class NQueen {


  public static void main(String[] args) {
    int n = 16;
    int nqueen = nqueen(n, 0, new int[n], 0);
    System.out.println("nqueen = " + nqueen);
  }


  /**
   * @param n   Lattice representing n * n
   * @param row How many lines are currently
   * @param res Use an array to record the column of the queen of each row
   * @param count Total results
   * @return
   */
  public static int nqueen(int n,int row,int[] res,int count){
    if (row == n){
      //Print
      print(n, res);
      count++;
      System.out.println("-----------");
      return count;
    }
    for (int col = 0; col < n; col++) {
      //Try putting the queen in this column first
      res[row] = col;
      //Judge whether it conflicts with the queen in the above line
      if (isOk(row,col,res)){
        //Iteration, next line
        count = nqueen(n,row+1,res,count);
      }
    }
    return count;
  }

  private static boolean isOk(int row, int col, int[] res) {
    for (int i = 0; i < row; i++) {
      //Judge the column of the queen of each row above. If it is the same as the current column, it is false
      if (res[i] == col){
        return false;
      }
      //Judge that the skimming and pressing directions are two straight lines with slopes of 1 and - 1, then their two coordinates | y2 - y1| == |x2 - x1|
      if (row - i == col - res[i] || row - i == res[i] - col ){
        return false;
      }
    }
    return true;
  }

  private static void print(int n, int[] res) {
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
        if (res[i] == j){
          System.out.print("Q");
        }else{
          System.out.print("*");
        }
        System.out.print(" ");
      }
      System.out.println();
    }
  }

}

Try, n=4

* Q * * 
* * * Q 
Q * * * 
* * Q * 
-----------
* * Q * 
Q * * * 
* * * Q 
* Q * * 
-----------
nqueen = 2

Try n=5

Q * * * * 
* * Q * * 
* * * * Q 
* Q * * * 
* * * Q * 
-----------
Q * * * * 
* * * Q * 
* Q * * * 
* * * * Q 
* * Q * * 
-----------
* Q * * * 
* * * Q * 
Q * * * * 
* * Q * * 
* * * * Q 
-----------
* Q * * * 
* * * * Q 
* * Q * * 
Q * * * * 
* * * Q * 
-----------
* * Q * * 
Q * * * * 
* * * Q * 
* Q * * * 
* * * * Q 
-----------
* * Q * * 
* * * * Q 
* Q * * * 
* * * Q * 
Q * * * * 
-----------
* * * Q * 
Q * * * * 
* * Q * * 
* * * * Q 
* Q * * * 
-----------
* * * Q * 
* Q * * * 
* * * * Q 
* * Q * * 
Q * * * * 
-----------
* * * * Q 
* Q * * * 
* * * Q * 
Q * * * * 
* * Q * * 
-----------
* * * * Q 
* * Q * * 
Q * * * * 
* * * Q * 
* Q * * * 
-----------
nqueen = 10

Topics: Java Algorithm