Set Matrix Zeroes in Rust

impl Solution {
    pub fn set_zeroes(matrix: &mut Vec<Vec<i32>>) {
        let m = matrix.len(); // Number of rows
        let n = matrix[0].len(); // Number of columns
        let mut first_row = false; // Flag to indicate if the first row needs to be set to 0
        let mut first_col = false; // Flag to indicate if the first column needs to be set to 0

        // Check if the first row contains any zeros
        for j in 0..n {
            if matrix[0][j] == 0 {
                first_row = true;
                break;
            }
        }

        // Check if the first column contains any zeros
        for i in 0..m {
            if matrix[i][0] == 0 {
                first_col = true;
                break;
            }
        }

        // Use the first row and first column to mark the rows and columns to be set to zero
        for i in 1..m {
            for j in 1..n {
                if matrix[i][j] == 0 {
                    matrix[i][0] = 0; // Mark the corresponding element in the first column
                    matrix[0][j] = 0; // Mark the corresponding element in the first row
                }
            }
        }

        // Set the marked rows and columns to zero (excluding the first row and first column)
        for i in 1..m {
            for j in 1..n {
                if matrix[i][0] == 0 || matrix[0][j] == 0 {
                    matrix[i][j] = 0;
                }
            }
        }

        // Set the first row to zero if necessary
        if first_row {
            for j in 0..n {
                matrix[0][j] = 0;
            }
        }

        // Set the first column to zero if necessary
        if first_col {
            for i in 0..m {
                matrix[i][0] = 0;
            }
        }
    }
}

PrevNext