알고리즘 공부
51. N-Queens
Sense.J
2020. 8. 20. 22:36
https://leetcode.com/problems/n-queens/
N-Queens - 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 {string[][]}
*/
var solveNQueens = function(n) {
var map = Array(n).fill(-1);
var res = [];
//var hash= {};
var colhash = Array(n).fill(0);
var save_map = function()
{
var tmp = [];
for( var i=0; i<n; ++i )
{
var Qpos = map[i];
var row = [];
for( var j=0; j<n; ++j )
{
if( j == Qpos) row.push("Q");
else row.push(".");
}
tmp.push(row.join(''));
}
res.push(tmp);
}
var chk = function()
{
for( var i=0; i<n; ++i )
{
for( var j=1; j<n-i; ++j )
{
// 우하
{
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() ) save_map();
}
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;
};