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.

click to show follow up.

Follow up:

Did you use extra space?
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution?

 
 1 public class Solution {
 2     public void setZeroes(int[][] matrix) {
 3         if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return;
 4         int row = 0, col = 0;
 5         boolean sig = true;
 6         for(int i = 0; i < matrix.length; i ++){
 7             for(int j = 0; j < matrix[0].length; j ++){
 8                 if(matrix[i][j] == 0){
 9                     if(sig){
10                         row = i;
11                         col = j;
12                         sig = false;
13                     } else {
14                         matrix[row][j] = 0;
15                         matrix[i][col] = 0;
16                     }
17                 }
18             }
19         }
20         if(sig) return;
21         for(int i = 0; i < matrix.length; i ++){
22             for(int j = 0; j < matrix[0].length; j ++){
23                 if((matrix[row][j] == 0 || matrix[i][col] == 0) && i != row && j != col) matrix[i][j] = 0;
24             }
25         }
26         for(int i = 0; i < matrix.length; i ++){
27             matrix[i][col] = 0;
28         }
29         for(int j = 0; j < matrix[0].length; j ++){
30             matrix[row][j] = 0;
31         }
32     }
33 }

 

posted on 2014-09-05 06:39  Step-BY-Step  阅读(160)  评论(0编辑  收藏  举报

导航