Set Matrix Zeroes

by atalaykutlay

Solution to "Set Matrix Zeroes" on Leetcode.

Set Matrix Zeroes
1class Solution:
2    def setZeroes(self, matrix: List[List[int]]) -> None:
3        """
4        Do not return anything, modify matrix in-place instead.
5        """
6
7        m = len(matrix)
8        n = len(matrix[0])
9        make_zero = []
10        for y in range(m):
11            for x in range(n):
12                if matrix[y][x] == 0:
13                    make_zero.append((x,y))
14        
15        for zero in make_zero:
16            x,y = zero
17
18            matrix[y] = [0] * n
19
20            for y_index in range(m):
21                matrix[y_index][x] = 0
22        

✨ Code Explanation ✨

This code is a solution to the "Set Matrix Zeroes" problem. The problem requires us to modify a given matrix in-place such that if any element in the matrix is 0, its entire row and column are set to 0. The code first defines the function setZeroes, which takes in a matrix as its input and does not return anything. The code then determines the number of rows and columns in the matrix using the len() function. Next, it initializes an empty list called make_zero. The code then loops through each element in the matrix using nested for loops. If an element is 0, its coordinates (x,y) are appended to the make_zero list. After that, the code iterates through each pair of coordinates (x,y) in the make_zero list. For each pair, it sets the entire row y of the matrix to all 0s using the statement matrix[y] = [0] * n. It then sets the entire column x of the matrix to 0 by looping through each row index y_index and setting matrix[y_index][x] to 0. In the end, the matrix is modified in-place such that all rows and columns containing 0s are set to 0.

Share

Share
Video
A cool 10 sec video.
Share
Detailed
Title, description, and syntax highlighted code.
Share
Simple
Syntax highlighted code with gradient background colored presentation.

Comments

It looks like there is no comment for this snippet. Leave the first one!
You need to login to send a comment.

Similar Snippets

Count Number of Texts
Count Number of Texts

Solution to "Count Number of Texts" question on Leetcode.

Language: python18 months ago
Quicksort in Python
Quicksort in Python

An easy quicksort implementation in Python.

Language: python19 months ago
Second Minimum Node In a Binary Tree
Second Minimum Node In a Binary Tree

Solution to "Second Minimum Node In a Binary Tree" on Leetcode.

Language: python17 months ago