leetcode--Set Matrix Zeroes

来源:互联网 发布:java gridlayout用法 编辑:程序博客网 时间:2024/06/03 16:44

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?


题意:给定m*n的矩阵,如果某个元素是0,使其同行,同列的所有元素为0

要求使用O(m+n)空间复制度,甚至常数空间


解法1:首先遍历第一行,如果找到0,做标记,说明第一行要清0

遍历第一列,如果找到0,做标记,说明第一列要清0

然后从(1,1)开始遍历矩阵,找到0,将对应的第一行,第一列的元素设置为0,用于标记该行列应该清0

最后,根据第一行,第一列,0的情况,清0

[java] view plain copy
  1. public class Solution {  
  2.     public void setZeroes(int[][] matrix) {  
  3.         int rows = matrix.length;  
  4.         int cols = matrix[0].length;  
  5.         boolean firstRow=false,firstCol=false;  
  6.         for(int i=0;i<rows;i++){  
  7.             if(matrix[i][0]==0){  
  8.                 firstRow = true;  
  9.                 break;  
  10.             }  
  11.         }  
  12.         for(int i=0;i<cols;i++){  
  13.             if(matrix[0][i]==0){  
  14.                 firstCol = true;  
  15.                 break;  
  16.             }  
  17.         }  
  18.         for(int i=1;i<rows;i++){  
  19.             for(int j=1;j<cols;j++){  
  20.                 if(matrix[i][j]==0){  
  21.                     matrix[i][0] = 0;  
  22.                     matrix[0][j] = 0;  
  23.                 }  
  24.             }  
  25.         }  
  26.         for(int i=1;i<rows;i++){  
  27.             if(matrix[i][0]==0){  
  28.                 for(int j=1;j<cols;j++){  
  29.                     matrix[i][j] = 0;  
  30.                 }  
  31.             }             
  32.         }  
  33.         for(int j=1;j<cols;j++){  
  34.             if(matrix[0][j]==0){  
  35.                 for(int i=1;i<rows;i++){  
  36.                     matrix[i][j] = 0;  
  37.                 }  
  38.             }             
  39.         }  
  40.         if(firstRow) for(int i=0;i<rows;i++) matrix[i][0] = 0;  
  41.         if(firstCol) for(int j=0;j<cols;j++) matrix[0][j] = 0;  
  42.     }  
  43. }  

原文链接http://blog.csdn.net/crazy__chen/article/details/46413689