矩阵置零

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/set-matrix-zeroes
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

要求把0所在的行和列的其他元素全部置零,可以先遍历矩阵,找到所有元素为0的位置并记录,再根据遍历的结果把其他的元素置零即可。

public void setZeroes(int[][] matrix) {
        int R = matrix.length;
        int C = matrix[0].length;
        Set<Integer> row = new HashSet<Integer>();
        Set<Integer> col = new HashSet<Integer>();
        
        for(int i = 0; i < R; i++)
        {
            for(int j = 0; j < C; j++)
            {
                if(matrix[i][j] == 0)
                {
                    row.add(i);
                    col.add(j);
                }
            }
        }
        
        for(int i = 0; i < R; i++)
        {
            for(int j = 0; j < C; j++)
            {
                if(row.contains(i) || col.contains(j))
                {
                    matrix[i][j] = 0;
                }
            }
        }
    }

 

posted on 2019-09-01 17:54  Jain_Shaw  阅读(152)  评论(0编辑  收藏  举报

导航