Queen's Attack II Discussions | Algorithms | HackerRank
  • + 0 comments

    JS solution: function queensAttack(n, k, r_q, c_q, obstacles) { // Write your code here const directions = { up: n - r_q, down: r_q - 1, left: c_q - 1, right: n - c_q, "up-right": Math.min(n - r_q, n - c_q), "up-left": Math.min(n - r_q, c_q - 1), "down-right": Math.min(r_q - 1, n - c_q), "down-left": Math.min(r_q - 1, c_q - 1) }

    obstacles.forEach(([r, c]) => {
        if(r === r_q) {
            if(c > c_q) {
                directions.right = Math.min(directions.right, c - c_q - 1);
            } else if(c < c_q) {
                directions.left = Math.min(directions.left, c_q - c - 1);
            }
        } else if(c === c_q) {
            if(r > r_q) {
                directions.up = Math.min(directions.up, r - r_q - 1);
            } else if (r < r_q) {
                directions.down = Math.min(directions.down, r_q - r -1);
            }
        } else if(Math.abs(r-r_q) === Math.abs(c - c_q)) {
            if(r > r_q && c > c_q) {
                directions["up-right"] = Math.min(directions["up-right"], r - r_q - 1);
            } else if(r > r_q && c < c_q) {
                directions["up-left"] = Math.min(directions["up-left"], r - r_q - 1);
            } else if (r < r_q && c < c_q) {
                directions["down-left"] = Math.min(directions["down-left"], r_q - r -1);
            } else if(r < r_q && c > c_q) {
                directions["down-right"] = Math.min(directions["down-right"], r_q - r -1);
            }
        }
    })
    
    return Object.values(directions).reduce((a, b) => a + b, 0);
    

    }