码迷,mamicode.com
首页 > 其他好文 > 详细

1.7 Matrix Zero

时间:2014-11-21 14:18:07      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:style   blog   ar   color   sp   for   div   log   bs   

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 }

 

1.7 Matrix Zero

标签:style   blog   ar   color   sp   for   div   log   bs   

原文地址:http://www.cnblogs.com/superbo/p/4112718.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!