• 1.7 Matrix Zero


    Write an algorithm such that if an element in an MxN matrix is 0, its
    entire rowand column are set to 0.

     1 public static void matrixZero(int[][] matrix) {
     2     if (matrix.length == 0 || matrix[0].length == 0)
     3         return;
     4 
     5     int m = matrix.length;
     6     int n = matrix[0].length;
     7     boolean rowZero = false;
     8     boolean colZero = false;
     9 
    10     // save first row and first col
    11     for (int i = 0; i < m; i++)
    12         if (matrix[i][0] == 0)
    13             rowZero = true;
    14     for (int i = 0; i < n; i++)
    15         if (matrix[0][i] == 0)
    16             colZero = true;
    17 
    18     for (int i = 0; i < m; i++) {
    19         for (int j = 0; j < n; j++) {
    20             if (matrix[i][j] == 0) {
    21                 matrix[i][0] = 0;
    22                 matrix[0][j] = 0;
    23             }
    24         }
    25     }
    26 
    27     for (int i = 1; i < m; i++) {
    28         if (matrix[i][0] == 0)
    29             for (int j = 1; j < n; j++) {
    30                 matrix[i][j] = 0;
    31             }
    32     }
    33 
    34     for (int i = 1; i < n; i++) {
    35         if (matrix[0][i] == 0)
    36             for (int j = 1; j < m; j++) {
    37                 matrix[j][i] = 0;
    38             }
    39     }
    40 
    41     if (rowZero) {
    42         for (int i = 0; i < m; i++)
    43             matrix[i][0] = 0;
    44     }
    45 
    46     if (colZero) {
    47         for (int i = 0; i < n; i++)
    48             matrix[0][i] = 0;
    49     }
    50 }
  • 相关阅读:
    不能说的话
    为什么书呆子不受欢迎
    Enum
    扩展方法
    若(p,q)=1,则(p^n,q^n)=1
    若a与m互质,则a不影响m的完全剩余组
    模m的剩余类里的一切数与m的最大公约数相等
    若p是与10互质的质数,则p-1个9能被p整除
    class.__subclasses__()
    权利要求书
  • 原文地址:https://www.cnblogs.com/superbo/p/4112718.html
Copyright © 2020-2023  润新知