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

    C# Solution

    public static int queensAttack(int n, int k, int r_q, int c_q, List<List<int>> obstacles)
    {
        if(n == 1)
            return 0;
        else
        {
            int moves = 0;
    
            HashSet<(int, int)> movements = new HashSet<(int, int)>()
            {
                ( 1,  0), // up
                (-1,  0), // down
                ( 0,  1), // right
                ( 0, -1), // left
                ( 1,  1), // right-up
                (-1,  1), // right-down
                ( 1, -1), // left-up
                (-1, -1)  // left-down
            };
    
            HashSet<(int, int)> obs = obstacles.Select(o => (o[0],o[1])).ToHashSet();
    
            foreach(var move in movements)
            {
                var response = 
                        CalculateMoves(n, k, r_q, c_q, obs, move.Item1, move.Item2);
                moves += response.moves;
                k = response.k;
            }
    
            return moves;
        }
    }
    
    public static (int moves, int k) 
        CalculateMoves(int n, int k, int r_q, int c_q, HashSet<(int, int)> o, 
        int rowOperation, int columnOperation)
    {
        int moves  = 0;
        int length = 1;
        int r_qNew = r_q;
        int c_qNew = c_q;
        while(length <= n)
        {
            r_qNew += rowOperation;
            c_qNew += columnOperation;
    
            if(r_qNew >= 1 && c_qNew >= 1 && r_qNew <= n && c_qNew <= n)
            {
                if(k >= 0 && o.Contains((r_qNew, c_qNew))) // obstacle found
                {
                    o.Remove((r_qNew, c_qNew));
                    length = n + 1;
                    k--;
    
                }
                else // no Obstacles found
                {
                    // add move and continue
                    moves++;
                    length++;
                }
    
            }
            else
            {
                // out of bounds
                // break the loop
                length = n + 1;
            }
    
        }
        return (moves, k);
    }