GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — coding-problems/Other/set_matrix_zeroes.py at master · bodeoni/coding-problems

Expand file tree

/

set_matrix_zeroes.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
83 lines (69 loc) · 1.71 KB
/

set_matrix_zeroes.py

Copy path

File metadata and controls

83 lines (69 loc) · 1.71 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
'''
Set Matrix Zeroes
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
Input:
[
[1,1,1],
[1,0,1],
[1,1,1]
]
Output:
[
[1,0,1],
[0,0,0],
[1,0,1]
]
=========================================
Use first column and first row for marking when 0 is found.
Time Complexity: O(N*M)
Space Complexity: O(1)
'''
############
# Solution #
############
def set_matrix_zeroes(matrix):
n = len(matrix)
if n == 0:
return
m = len(matrix[0])
# check if 0 exist in first row
is_row = False
for j in range(m):
if matrix[0][j] == 0:
is_row = True
# check if 0 exist in first column
is_col = False
for i in range(n):
if matrix[i][0] == 0:
is_col = True
# find which columns and rows should be 0
for i in range(1, n):
for j in range(1, m):
if matrix[i][j] == 0:
matrix[i][0] = matrix[0][j] = 0
# set 0 if the row or column where this element is located is 0
for i in range(1, n):
for j in range(1, m):
if (matrix[i][0] == 0) or (matrix[0][j] == 0):
matrix[i][j] = 0
# fill the first row with 0 if needed
if is_row:
for j in range(m):
matrix[0][j] = 0
# fill the first column with 0 if needed
if is_col:
for i in range(n):
matrix[i][0] = 0
###########
# Testing #
###########
# Test 1
# Correct result => [[0, 0, 0, 0], [0, 4, 5, 0], [0, 3, 1, 0]]
mat = [[0, 1, 2, 0], [3, 4, 5, 2], [1, 3, 1, 5]]
set_matrix_zeroes(mat)
print(mat)
# Test 2
# Correct result => [[1, 0, 1], [0, 0, 0], [1, 0, 1]]
mat = [[1, 1, 1], [1, 0, 1], [1, 1, 1]]
set_matrix_zeroes(mat)
print(mat)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.