- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Knights' Attack in Python
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
0 | 0 | 0 | 0 | 0 |
0 | 1 | 0 | 0 | 0 |
0 | 0 | 0 | 1 | 0 |
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
- if nr is in range of row and nc is in range of col and A[nr, nc] 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 A[r][c] is non-zero, then
- for c in range 0 to col-1, do
- return False
Let us see the following implementation to get better understanding −
Example
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
- Related Articles
- Place K-knights such that they do not attack each other in C++
- What is difference between '.' , '?' and '*' in Python regular expression?
- Difference between Active Attack and Passive Attack
- What does 'in' operator do in Python?
- What does colon ':' operator do in Python?
- What does 'is' operator do in Python?
- What does 'not in' operator do in Python?
- What is a Ping Flood Attack or ICMP Flood Attack?
- The 51% Attack
- Cyber Attack Symptoms
- Rundll32.exe Attack
- What does 'is not' operator do in Python?
- Check if a Queen can attack a given cell on chessboard in Python
- Program to find number of string we can make where 'a' can be 'a' or 'b', and 'b' remains 'b'in Python
- How can I set the 'backend' in matplotlib in Python?

Advertisements