搜索此博客

2012年8月8日星期三

Set Matrix Zeros

This is a well known problem in the book "Cracking the Coding Interview (Careercup 150)", Also seen on LeetCode

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

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?


01 public void setZeroes(int[][] matrix) {
02
03  int m=matrix.length;
04  int n=matrix[0].length;
05  boolean row1IsZero=false;
06  boolean col1IsZero=false;
07
08  for(int j=0;j<n;j++)
09  {
10    if(matrix[0][j]==0)
11    {
12      row1IsZero=true;
13      break;
14    }
15  }
16
17  for(int i=0;i<m;i++)
18  
19  {
20    if(matrix[i][0]==0)
21    {
22      col1IsZero=true;
23      break;
24    }
25  }
26
27  for(int i=1;i<m;i++)
28  {
29    for(int j=1;j<n;j++)
30    {
31      if(matrix[i][j]==0)
32      {
33        matrix[i][0]=0;
34        matrix[0][j]=0;
35      }
36    }
37  }
38
39  for(int i=1;i<m;i++)
40  {
41    for(int j=1;j<n;j++)
42    {
43      if(matrix[i][0]==0 || matrix [0][j]==0)
44      {
45        matrix[i][j]=0;
46      }
47    }
48  }
49  if(row1IsZero)
50  {
51    for(int j=0;j<n;j++)
52    {
53      matrix[0][j]=0;
54    }
55  }
56  if(col1IsZero)
57  {
58    for(int i=0;i<m;i++)
59    {
60      matrix[i][0]=0;
61    }
62  }
63
64 }

2 条评论:

  1. 此评论已被作者删除。

    回复删除
  2. 这题我做了无数次才AC。关键在于,make sure the data you read is not "dirty". 加油~~

    回复删除