Blind 75

Set Matrix Zeroes

Problem
LC 73
Category
Matrix
File
blind75_LC73SetMatrixZeroes.java
Path
pkg5leetcode/blind75/blind75_LC73SetMatrixZeroes.java
Package
pkg5leetcode.blind75
Command
java pkg5leetcode/blind75/blind75_LC73SetMatrixZeroes.java
Approach
Use first row/col as markers; handle row0/col0 separately.
Complexity
Time O(mn), Space O(1)

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/blind75/blind75_LC73SetMatrixZeroes.java
1package pkg5leetcode.blind75;2 3/*4 * Set Matrix Zeroes | LC 735 * APPROACH: Use first row/col as markers; handle row0/col0 separately.6 * COMPLEXITY: Time O(mn), Space O(1)7 */8public class blind75_LC73SetMatrixZeroes {9    static void setZeroes(int[][] matrix) {10        int m = matrix.length, n = matrix[0].length;11        boolean row0 = false, col0 = false;12        for (int j = 0; j < n; j++) if (matrix[0][j] == 0) row0 = true;13        for (int i = 0; i < m; i++) if (matrix[i][0] == 0) col0 = true;14        for (int i = 1; i < m; i++)15            for (int j = 1; j < n; j++)16                if (matrix[i][j] == 0) { matrix[i][0] = 0; matrix[0][j] = 0; }17        for (int i = 1; i < m; i++)18            for (int j = 1; j < n; j++)19                if (matrix[i][0] == 0 || matrix[0][j] == 0) matrix[i][j] = 0;20        if (row0) for (int j = 0; j < n; j++) matrix[0][j] = 0;21        if (col0) for (int i = 0; i < m; i++) matrix[i][0] = 0;22    }23 24    public static void main(String[] args) {25        int[][] m1 = {{1, 1, 1}, {1, 0, 1}, {1, 1, 1}};26        setZeroes(m1);27        check(m1[1][0] == 0 && m1[1][2] == 0, "case1");28        int[][] m2 = {{0, 1, 2, 0}, {3, 4, 5, 2}, {1, 3, 0, 5}};29        setZeroes(m2);30        check(m2[0][0] == 0 && m2[2][2] == 0, "case2");31        System.out.println("all tests passed");32    }33 34    static void check(boolean cond, String name) {35        if (!cond) throw new AssertionError("FAILED: " + name);36        System.out.println("  PASS " + name);37    }38}