集册 Java实例教程 给定一个布尔矩阵,更新它,以便如果任何单元格为真,则该单元格中的所有行和列都为真。

给定一个布尔矩阵,更新它,以便如果任何单元格为真,则该单元格中的所有行和列都为真。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

506
给定一个布尔矩阵,更新它,以便如果任何单元格为真,则该单元格中的所有行和列都为真。

import java.util.Arrays;


public class ZeroMatrix {

    public static void zeroMatrix(boolean[][] matrix) {/*时   代    Java - nowjava.com*/


        // Verify the input array is nonzero

        if (matrix.length == 0 || matrix[0].length == 0)

            return;


        // Determine whether the first row or first column is true

        boolean rowZero = false, colZero = false;

        for (boolean i : matrix[0]) {

            rowZero |= i;

        }

        for (boolean[] i : matrix) {

            colZero |= i[0];

        }/**来 自 n o w j a v a . c o m**/


        // For each cell not in the first row/column, if it is true, set the 

        // cell in the first row/same column and first column/same row to be 

        // true

        for (int i = 1; i < matrix.length; i++) {

            for (int j = 1; j < matrix[0].length; j++) {

                if (matrix[i][j]) {

                    matrix[i][0] = true;

                    matrix[0][j] = true;

                }

            }

        }


        // Go through the first column and set each row to true where cell in

        // the first column is true

        for (int i = 1; i < matrix.length; i++) {

            if (matrix[i][0]) {

                for (int j = 1; j < matrix[i].length; j++) {

                    matrix[i][j] = true;

                }

            }

        }


        // Repeat for the rows

        for (int j = 1; j < matrix[0].length; j++) {

            if (matrix[0][j]) {

                for (int i = 1; i < matrix.length; i++) {

                    matrix[i][j] = true;

                }

            }

        }


        // Set first row/column to true if necessary

        if (rowZero) {

            for (int i = 0; i < matrix[0].length; i++) {

                matrix[0][i] = true;

            }

        }


        if (colZero) {

            for (int i = 0; i < matrix.length; i++) {

                matrix[i][0] = true;

            }

        }

    }


    // Sample test cases

    public static void main(String[] args) {

        boolean[][] a = new boolean[][] { { true, false, false },

                { false, false, false }, { false, false, false } };

        zeroMatrix(a);

        assert compare2dArrays(a, new boolean[][] { { true, true, true },

                { true, false, false }, { true, false, false } }) : "First row and first column";


        a = new boolean[][] { { false, false, false },

                { false, false, false }, { false, false, false } };

        zeroMatrix(a);

        assert compare2dArrays(a, new boolean[][] {

                { false, false, false }, { false, false, false },

                { false, false, false } }) : "All false";


    }


    private 
展开阅读全文