
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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 Articles
- Flip the matrix horizontally and invert it using JavaScript
- How to invert a matrix or nArray in Python?
- 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
- How to flip an image in OpenCV Python?
- How to invert the elements of a boolean array in Python?
- How to invert case for all letters in a string in Python?
- Matrix and linear Algebra calculations in Python
- Flip Columns For Maximum Number of Equal Rows in Python
- Matrix manipulation in Python
- Initialize Matrix in Python
- Rotate Matrix in Python

Advertisements