# Flip and Invert Matrix in Python

PythonServer Side ProgrammingProgramming

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
• track := track + 1
• return mat

Let us see the following implementation to get better understanding −

## Example

Live Demo

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]]
Published on 23-Sep-2020 06:37:41