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

    I came with practically the same solution in PHP, but I had time limit exceptions for the biggest inputs. What Python does diferently from PHP? Is it the "in_array" function that have different big-O's?

    function queensAttack(`$n, $`k, `$r_q, $`c_q, $obstacles) {
        // North
        $north = 0;    
        for(`$i = $`r_q + 1; `$i <= $`n; $i++) {
            `$field = [$`i, $c_q];
            if(in_array(`$field, $`obstacles)) {
                break;
            }
            $north++;
        }
    
        // South
        $south = 0;    
        for(`$i = $`r_q - 1; `$i > 0; $`i--) {
            `$field = [$`i, $c_q];
            if(in_array(`$field, $`obstacles)) {
                break;
            }
            $south++;
        }
    
        // East
        $east = 0;    
        for(`$i = $`c_q + 1; `$i <= $`n; $i++) {
            `$field = [$`r_q, $i];
            if(in_array(`$field, $`obstacles)) {
                break;
            }
            $east++;
        }
    
        // West
        $west = 0;    
        for(`$i = $`c_q - 1; `$i > 0; $`i--) {
            `$field = [$`r_q, $i];
            if(in_array(`$field, $`obstacles)) {
                break;
            }
            $west++;
        }
    
        // North-East
        $ne = 0;
        `$r = $`r_q + 1;
        `$c = $`c_q + 1;
        while(`$r <= $`n && `$c <= $`n) {
            `$field = [$`r, $c];
            if(in_array(`$field, $`obstacles)) {
                break;
            }
            $ne++;
            $r++;
            $c++;
        }
    
        // South-West
        $sw = 0;
        `$r = $`r_q - 1;
        `$c = $`c_q - 1;
        while(`$r > 0 && $`c > 0) {
            `$field = [$`r, $c];
            if(in_array(`$field, $`obstacles)) {
                break;
            }
            $sw++;
            $r--;
            $c--;
        }
    
        // North-West
        $nw = 0;
        `$r = $`r_q + 1;
        `$c = $`c_q - 1;
        while(`$r <= $`n && $c > 0) {
            `$field = [$`r, $c];
            if(in_array(`$field, $`obstacles)) {
                break;
            }
            $nw++;
            $r++;
            $c--;
        }
    
        // South-East
        $se = 0;
        `$r = $`r_q - 1;
        `$c = $`c_q + 1;
        while(`$r > 0 && $`c <= $n) {
            `$field = [$`r, $c];
            if(in_array(`$field, $`obstacles)) {
                break;
            }
            $se++;
            $r--;
            $c++;
        }
    
        return (
            $north +
            $south +
            $east +
            $west +
            $ne +
            $sw + 
            $nw +
            $se
        );
    }