Leetcode OJ 73 Set Matrix Zeroes [Medium]

来源:互联网 发布:服装设计淘宝 编辑:程序博客网 时间:2024/04/27 00:26

题目描述:

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.

题目理解:

给定一个m*n的矩阵,如果一个元素是0,则这个元素所在的行和列全都置为0。

测试用例:

功能测试:只有一行的矩阵,包含/不包含0;只有一列的矩阵,包含/不包含0;m*n矩阵,0在/不在第一行/列;

特殊输入:输入是空;

分析:

1.首先遍历整个矩阵,找到为0的元素,一定是必须的。

2.一找到0元素就置行列为0,会影响找其他0元素,因此一定是遍历这个矩阵,找到0元素并记下该0元素的行列值。

3.将第一行和第一列的元素作为标记值,用来记录0元素的行、列值。

4.对于非第一行、列的元素:

       遍历整个矩阵,0元素所在位置为matrix[row][col],则设置matrix[row][0]和matrix[0][col]为0;

       遍历完后重置矩阵,先不管第一行和列,从[1,1]开始到[m,n],如果所在位置的元素的对应matrix[row][0]或者matrix[0][col]为0,则将该位置置为0;

5.对于第一行、列的元素:

       遍历矩阵时,如果该元素在第一行,则boolean值firstrow设置为true,如果如果该元素在第一列,则boolean值firstcol设置为true;

       在设置完矩阵的[1,1]开始到[m,n]元素后,再设置第一行和列,如果firstrow为true,则第一行全部置为0,如果firstcol为true,则第一列全部置为0;

解答:

 public static void setZeroes(int[][] matrix) {        boolean firstcol = false,firstrow = false;        for(int row = 0; row < matrix.length; row++){            for(int col = 0; col < matrix[0].length; col++){                if(matrix[row][col] == 0){                    if(row == 0) firstrow = true;                    if(col == 0) firstcol = true;                    matrix[row][0] = 0;                    matrix[0][col] = 0;                }            }        }        for(int row = 1; row < matrix.length; row ++){            for(int col = 1; col < matrix[0].length; col ++){                if(matrix[row][0] == 0 || matrix[0][col] == 0)                    matrix[row][col] = 0;            }        }        if(firstcol == true){            for(int row = 0; row < matrix.length; row ++){                matrix[row][0] = 0;            }        }        if(firstrow == true){            for(int col = 0; col < matrix[0].length; col ++){                matrix[0][col] = 0;            }        }    }