首页 > 其他 > 详细

Leetcode 73: Set Matrix Zeroes

时间:2017-11-11 11:09:28      阅读:268      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/liangmou/p/7818033.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!