Knights' Attack in Python

PythonServer Side ProgrammingProgramming

Suppose we have a two-dimensional binary matrix, representing a rectangular chess board, here 0 is for empty cell and 1 is for a knight. The knight is able to move two squares away horizontally and one square vertically, or two squares vertically and one square horizontally (like chess board knight). We have to check whether any two knights are attacking each other or not.

So, if the input is like

00000
01000
00010

Then the output will be True

To solve this, we will follow these steps −

  • row, col := row count of matrix, column count of matrix
  • for r in range 0 to row-1, do
    • for c in range 0 to col-1, do
      • if A[r][c] is non-zero, then
        • for each nr, nc in [(r+1, c-2), (r+1, c+2), (r+2, c-1), (r+2, c+1)], do
          • if nr is in range of row and nc is in range of col and A[nr, nc] is non-zero, then
            • return True
  • return False

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, A):
      row, col = len(A), len(A[0])
      for r in range(row):
         for c in range(col):
            if A[r][c]:
               for nr, nc in ((r+1, c-2), (r+1, c+2), (r+2, c-1), (r+2, c+1)):
                  if 0 <= nr < row and 0 <= nc <col and
                     A[nr][nc]:
                     return True
      return False
ob = Solution()
mat = [[0,0,0,0,0],
[0,1,0,0,0],
[0,0,0,1,0]]
print(ob.solve(mat))

Input

[[0,0,0,0,0],
[0,1,0,0,0],
[0,0,0,1,0]]

Output

True
raja
Published on 23-Sep-2020 07:27:36

Advertisements