Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Knights' Attack in Python
The knight attack problem checks if any two knights on a chessboard can attack each other. A knight moves in an L-shape: two squares in one direction and one square perpendicular, or vice versa.
Problem Understanding
Given a binary matrix where 0 represents an empty cell and 1 represents a knight, we need to determine if any two knights are attacking each other.
For the input matrix:
| 0 | 0 | 0 | 0 | 0 |
| 0 | 1 | 0 | 0 | 0 |
| 0 | 0 | 0 | 1 | 0 |
The output is True because the knight at position (1,1) can attack the knight at position (2,3).
Knight Movement Pattern
A knight can move to 8 possible positions from any given cell. However, we only need to check 4 directions to avoid duplicate checking:
Algorithm Steps
To solve this problem, we follow these steps:
- Iterate through each cell in the matrix
- For each knight found (cell value = 1), check 4 possible attack positions
- The 4 positions are: (r+1, c-2), (r+1, c+2), (r+2, c-1), (r+2, c+1)
- If any attack position contains another knight, return True
- If no attacking knights are found, return False
Implementation
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]: # Found a knight
# Check 4 possible attack positions
for nr, nc in ((r+1, c-2), (r+1, c+2), (r+2, c-1), (r+2, c+1)):
# Check if position is within bounds and has a knight
if 0 <= nr < row and 0 <= nc < col and A[nr][nc]:
return True
return False
# Test with the given example
ob = Solution()
mat = [[0,0,0,0,0],
[0,1,0,0,0],
[0,0,0,1,0]]
print(ob.solve(mat))
True
How It Works
In the example matrix, there's a knight at position (1,1) and another at position (2,3). When we check the knight at (1,1), one of its possible attack positions is (1+1, 1+2) = (2,3), which contains another knight. Therefore, the function returns True.
Time Complexity
The time complexity is O(m × n) where m and n are the dimensions of the matrix, as we visit each cell once and perform constant time operations for each knight found.
Conclusion
This algorithm efficiently detects knight attacks by checking only 4 of the 8 possible knight moves from each position. The approach avoids duplicate checking and provides an optimal solution for the knight attack problem.
