N-Queens II @ LeetCode

Source: Internet
Author: User

Is the follow-up of the previous question. There are several methods in total. It is easy to use global variables, but in java, primitive parameters cannot be easily passed by reference or pointer as C ++. So I think it is better to use return value to record the number of methods!

Package Level4; import java. util. arrayList;/*** N-Queens II ** Follow up for N-Queens problem. ** Now, instead outputting board configurations, return the total number of * distinct solutions. ** http://www.leetcode.com/wp-content/uploads/2012/03/8-queens.png **/public class S52 {public static void main (String [] args) {System. out. println (totalNQueens (8);} public static int totalNQueens (int n) {int [] queenList = new int [n]; return placeQueen (queenList, 0, n );} // recursively backtrack the eight queens. The key record is the public static int placeQueen (int [] queenList, int row, int n) {// Base Case, if (row = n) {return 1;} int cnt = 0; // start searching for this row // traverse all columns in the row, test which location is safe for (int col = 0; col <n; col ++) {if (isSafe (queenList, row, col )) {queenList [row] = col; cnt + = placeQueen (queenList, row + 1, n) ;}} return cnt ;}// determine whether the coordinates are (row, col) is safe (check rows, columns, positive and negative diagonal lines) // stores rows and column coordinates pair in the queenList, that is, queenList [row] = col public static boolean isSafe (int [] queenList, int row, int col) {for (int preRow = 0; preRow <row; preRow ++) {int preCol = queenList [preRow]; if (preRow = row) {// theoretically no check is required, because preRow is always less than the return false of row ;} if (preCol = col) {// check whether return false is in the same column;} if (row-preRow = col-preCol) {// return false on the diagonal line ;} if (preRow + preCol = row + col) {// return false on the diagonal line;} return true ;}}

 


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.