알고리즘 공부
2020. 8. 20. 22:37
https://leetcode.com/problems/n-queens-ii/
N-Queens II - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
/**
* @param {number} n
* @return {number}
*/
var totalNQueens = function(n) {
var map = Array(n).fill(-1);
var res = 0;
var colhash = Array(n).fill(0);
var chk = function()
{
for( var i=0; i<n; ++i )
{
for( var j=1; j<n-i; ++j )
{
// 우하
if( i+j < n )
{
if( map[i]+j == map[i+j] || map[i]-j == map[i+j] )
return false;
}
// 좌하
if( i-j > 0 )
{
if( map[i]+j == map[i-j] || map[i]-j == map[i-j] )
return false;
}
}
}
return true;
}
var find = function( p_idx )
{
if( p_idx == n )
{
if( chk() ) ++res;
}
else
{
for( var i=0; i<n; ++i )
{
if( !colhash[i] )
{
colhash[i] = 1;
map[p_idx]= i;
if( p_idx+1 <= n ) find(p_idx+1);
map[p_idx]= -1;
colhash[i] = 0;
}
}
}
}
find(0);
return res;
};