Last updated on August 5th, 2024 at 12:42 am
Here, We see Set Matrix Zeroes LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.
List of all LeetCode Solution
Topics
Array
Companies
Amazon, Microsoft
Level of Question
Medium
Set Matrix Zeroes LeetCode Solution
Table of Contents
Problem Statement
Given an m x n
integer matrix matrix
, if an element is 0
, set its entire row and column to 0
‘s.
You must do it in place.
Example 1: Input: matrix = [[1,1,1],[1,0,1],[1,1,1]] Output: [[1,0,1],[0,0,0],[1,0,1]] Example 2: Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]] Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]
1. Set Matrix Zeroes Leetcode Solution C++
class Solution { public: void setZeroes(vector<vector<int>>& matrix) { int m=matrix.size(); int n=matrix[0].size(); vector<pair<int,int>> cor; for(int i=0;i<m;i++) { for(int j=0;j<n;j++) { if(matrix[i][j]==0) { cor.push_back({i,j}); } } } for(int i=0;i<cor.size();i++) { int x=cor[i].first; int y=cor[i].second; int row=0; int col=0; while(row<m) { matrix[row][y]=0; row++; } while(col<n) { matrix[x][col]=0; col++; } } } };
2. Set Matrix Zeroes Leetcode Solution Java
class Solution { public void setZeroes(int[][] matrix) { int m = matrix.length, n = matrix[0].length, k = 0; while (k < n && matrix[0][k] != 0) ++k; for (int i = 1; i < m; ++i) for (int j = 0; j < n; ++j) if (matrix[i][j] == 0) matrix[0][j] = matrix[i][0] = 0; for (int i = 1; i < m; ++i) for (int j = n - 1; j >= 0; --j) if (matrix[0][j] == 0 || matrix[i][0] == 0) matrix[i][j] = 0; if (k < n) Arrays.fill(matrix[0], 0); } }
3. Set Matrix Zeroes Leetcode Solution JavaScript
var setZeroes = function(matrix) { let isCol = false, r = matrix.length, c = matrix[0].length; for (let i = 0; i < r; i++) { if (!matrix[i][0]) isCol = true; for (let j = 1; j < c; j++) { if (!matrix[i][j]) { matrix[i][0] = 0; matrix[0][j] = 0; }; } } for (let i = 1; i < r; i++) { for (let j = 1; j < c; j++) { if (!matrix[i][0] || !matrix[0][j]) matrix[i][j] = 0; } } if (!matrix[0][0]) { for (let j = 0; j < c; j++) matrix[0][j] = 0; } if (isCol) { for (let i = 0; i < r; i++) { matrix[i][0] = 0; } } };
4. Set Matrix Zeroes Leetcode Solution Python
class Solution(object): def setZeroes(self, matrix): row = set() column = set() for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] == 0: row.add(i) column.add(j) for i in row: for j in range(len(matrix[0])): matrix[i][j] = 0 for i in column: for j in range(len(matrix)): matrix[j][i] = 0