http://codingweihung.blogspot.com/2015/08/leetcodebacktracking-n-queens-sanpchat.html
2. How
http://codingweihung.blogspot.com/2015/08/leetcodebacktracking-n-queens-sanpchat.html
NOTE: return total number of distinct solution
What is distinct solution?
how to represent a solution? a String[], so distinct means different String[]
hashSet to store string array ? to much hassle
hashSet to store int array which is columnWithQueenForRow
public class Solution { // NOTE: can also declare a global variable int res, initialize in totalNQueens() and increment in helper() public int totalNQueens(int n) { int[] res = {0}; /*validate the input */ if ( n <= 0) { return res[0]; } int[] columnWithQueenForRow = new int[n]; helper(n, 0, columnWithQueenForRow, res); } /*recursive function to go over column by column*/ private void helper (int size, int row , int[] ColumnWithQueenForRow, int[] res) { if ( row == n ) { /*NOTE: won;t have duplicate solution since start from different column*/ res[0]+=1; return; } for (int j = 0 ; j < n ;j++) { columnWithQueenForRow[row] = j; if ( check(row, columnWithQueenForRow) ) { helper( n, row+1, columnWithQueenForRow, ); } } } /* check valid move*/ private boolean check (int row, int[] columnWithQueenForRow) { for ( int i = 0 ; i < row; i++) { if ( columnWithQueenForRow[row] == columnWithQueenForRow[i] || Math.abs( columnWithQueenForRow[row] - columnWithQueenForRow[i] ) == (row - i) ) { return false; } } return true; } }
No comments:
Post a Comment