
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Flip and Invert Matrix in Python
Suppose we have a binary matrix mat. We have to select each row in matrix, then reverse the row. After that, flip each bit (0 to 1 and 1 to 0).
So, if the input is like
1 | 1 | 0 |
0 | 1 | 0 |
0 | 0 | 1 |
then the output will be
1 | 0 | 0 |
1 | 0 | 1 |
0 | 1 | 1 |
To solve this, we will follow these steps −
- track:= 0
- for each row in mat, do
- reverse the row
- tracker := 0
- for each val in row, do
- if val is 1, then
- mat[track, tracker] := 0
- otherwise,
- mat[track, tracker] := 1
- tracker := tracker + 1
- if val is 1, then
- track := track + 1
- return mat
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, mat): track=0 for row in mat: row.reverse() tracker = 0 for val in row: if val == 1: mat[track][tracker] = 0 else: mat[track][tracker] = 1 tracker += 1 track += 1 return mat ob = Solution() mat = [[1,1,0],[0,1,0],[0,0,1]] print(ob.solve(mat))
Input
[[1,1,0],[0,1,0],[0,0,1]]
Output
[[1, 0, 0], [1, 0, 1], [0, 1, 1]]
- Related Questions & Answers
- Flip the matrix horizontally and invert it using JavaScript
- Random Flip Matrix in C++
- Invert Binary Tree in Python
- 123 Number Flip in Python
- Program to invert a binary tree in Python
- Python - Ways to invert mapping of dictionary
- Flip-flop types and their Conversion in C++
- Digital Electronics Flip-flops and their Types
- Set Invert Effect with CSS
- bitset::flip() in C++ STL
- Flip to Zeros in C++
- Flip Game II in C++
- Flip Columns For Maximum Number of Equal Rows in Python
- Invert Result of MongoDB Query (Implement Opposite of $and operation)?
- How to invert case for all letters in a string in Python?
Advertisements