Queen's Attack II Discussions | Algorithms | HackerRank
We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Hi, a solution in JS:
algorithm:
1. find all the squares the queen can attack initially (total variable in code)
2. iterate through the obstacles array, and for each obstacle, i first check if it is blocking the queen from attacking by veryfing of any obstacle is in one of the 8 paths the queen can attack, if so i calculate how many squares this obstacles block (block variable in code)
and then i substract this value from the total.
3. pay attention that there might be more than 1 obstacle in a certain direction/path, so you want to make sure you dont substract more than you need(thats why i have the max's variables)
function queensAttack(n, k, r_q, c_q, obstacles) {
let left = c_q - 1;
let right = n - c_q;
let up = n - r_q;
let down = r_q - 1;
let leftDown = Math.min(left, down);
let leftUp = Math.min(left, up);
let rightDown = Math.min(right, down);
let rightUp = Math.min(right, up);
let total = left + right + up + down + leftUp + leftDown + rightUp + rightDown;
let maxL = 0, maxR = 0, maxU = 0,maxD = 0, maxLU = 0, maxLD = 0, maxRD = 0, maxRU = 0;
let r, c, block, temp = 0;
for(let i = 0; i < k; i++) {
Queen's Attack II
You are viewing a single comment's thread. Return to all comments →
Hi, a solution in JS: algorithm: 1. find all the squares the queen can attack initially (total variable in code) 2. iterate through the obstacles array, and for each obstacle, i first check if it is blocking the queen from attacking by veryfing of any obstacle is in one of the 8 paths the queen can attack, if so i calculate how many squares this obstacles block (block variable in code) and then i substract this value from the total. 3. pay attention that there might be more than 1 obstacle in a certain direction/path, so you want to make sure you dont substract more than you need(thats why i have the max's variables)
function queensAttack(n, k, r_q, c_q, obstacles) { let left = c_q - 1; let right = n - c_q; let up = n - r_q; let down = r_q - 1; let leftDown = Math.min(left, down); let leftUp = Math.min(left, up); let rightDown = Math.min(right, down); let rightUp = Math.min(right, up); let total = left + right + up + down + leftUp + leftDown + rightUp + rightDown; let maxL = 0, maxR = 0, maxU = 0,maxD = 0, maxLU = 0, maxLD = 0, maxRD = 0, maxRU = 0; let r, c, block, temp = 0; for(let i = 0; i < k; i++) {
}