Leetcode 73: Set Matrix Zeroes

Posted Keep walking

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 73: Set Matrix Zeroes相关的知识,希望对你有一定的参考价值。

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

 

Note: it‘s a pretty tricky problem, hard to be bug free.

 

 1 public class Solution {
 2     public void SetZeroes(int[,] matrix) {
 3         int m = matrix.GetLength(0), n = matrix.GetLength(1);
 4         
 5         bool firstColumn = false;
 6         for (int i = 0; i < m; i++)
 7         {
 8             if (matrix[i, 0] == 0)
 9             {
10                 firstColumn = true;
11                 break;
12             }
13         }
14         
15         for (int i = 0; i < m; i++)
16         {
17             for (int j = 1; j < n; j++)
18             {
19                 if (matrix[i, j] == 0)
20                 {
21                     matrix[i, 0] = 0;
22                     matrix[0, j] = 0;
23                 }
24             }
25         }
26         
27         for (int i = m - 1; i >= 0 ; i--)
28         {            
29             for (int j = n - 1; j >= 1; j--)
30             {
31                 if (matrix[i, 0] == 0 || matrix[0, j] == 0)
32                 {
33                     matrix[i, j] = 0;
34                 }
35             }
36                         
37             if (firstColumn) matrix[i, 0] = 0;
38         }
39     }
40 }

 

以上是关于Leetcode 73: Set Matrix Zeroes的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 73. Set Matrix Zeroes

[leetcode]73.Set Matrix Zeroes

Leetcode 73: Set Matrix Zeroes

[leetcode][73] Set Matrix Zeroes

leetcode 73 Set Matrix Zeroes ----- java

[LeetCode] 73. Set Matrix Zeroes Java