Grid Illumination in Python

PythonServer Side ProgrammingProgramming

Suppose we have a N x N grid of cells, in each cell (x, y) there is a lamp. Initially, some of the lamps are on. The lamps[i] is the location of the i-th lamp that is on. Each lamp that is on glows every square on its x-axis, y-axis, and both diagonals. Now for the i-th query i.e. queries[i] = (x, y), the answer to the query is 1 if the cell (x, y) is glowed, otherwise 0. After each query (x, y), we turn off any lamps that are at cell (x, y) or are adjacent 8-directionally. Return an array of answers. Each value answer[i] should be equal to the answer of the i-th query queries[i].

So, if the input is like N = 5, lamps are [[0,0],[4,4]], query = [[1,1],[1,0]], then the output will be [1,0]

To solve this, we will follow these steps −

  • lamps := set of pairs from the given array lamps

  • Create maps x, y, diag1, diag2

  • for each pair (i, j) in lamps

    • x[i] := x[i] + 1, y[j] := y[j] + 1

    • diag1[i + j] := diag1[i + j] + 1, diag2[i - j] = diag2[i - j] + 1

  • ans := []

  • for each value i in C

    • a := i[0], b := i[1]

    • insert (1 if x[a] + y[b] + diag1[a + b] + diag2[a - b] > 0 otherwise 0) into ans

    • for row in range a - 1 to a + 1

      • for col in range b - 1 to b + 1

        • if row, col pair is in lamps, then −

          • x[row] := x[row] - 1

          • y[col] := y[col] - 1

          • diag1[row + col] = diag1[row + col] - 1

          • diag2[row - col] = diag2[row - col] - 1

          • remove(row, col) from lamps

  • return ans

Let us see the following implementation to get better understanding −

Example

from collections import defaultdict
class Solution(object):
   def gridIllumination(self, N, b, C):
      lamps = {(i[0], i[1]) for i in b}
      x, y, diag1, diag2 = defaultdict(int), defaultdict(int),
defaultdict(int), defaultdict(int)
      for i, j in lamps:
         x[i] += 1
         y[j] += 1
         diag1[i + j] += 1
         diag2[i - j] += 1
      ans = []
      for i in C:
         a = i[0]
         b = i[1]
         ans.append(1 if x[a] + y[b] + diag1[a + b] + diag2[a - b] > 0 else 0)
         for row in range( a - 1, a + 2):
            for col in range(b - 1, b + 2):
               if (row, col) in lamps:
                  x[row] -= 1
                  y[col] -= 1
                  diag1[row + col] -= 1
                  diag2[row - col] -= 1
                  lamps.remove((row, col))
         return ans
ob = Solution()
N = 5
lamps = [[0,0],[4,4]]
query = [[1,1],[1,0]]
print(ob.gridIllumination(N, lamps, query))

Input

5, [[0,0],[4,4]], [[1,1],[1,0]]

Output

[1, 0]
raja
Updated on 04-Jun-2020 10:49:36

Advertisements