首页 > 代码库 > [leetcode] Set Matrix Zeroes

[leetcode] 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.

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?

https://oj.leetcode.com/problems/set-matrix-zeroes/

 

最佳思路:就是先遍历二维数组,然后用首行和首列作为标记是否整行整列要设为0。对于首行首列本身,另用两个boolean记录。

 

public class Solution {    public void setZeroes(int[][] matrix) {        if(matrix==null||matrix.length==0||matrix[0].length==0)            return;        int m=matrix.length;        int n=matrix[0].length;                int i,j;        boolean isFirstRowZero=false;        boolean isFirstColZero=false;        for(i=0;i<m;i++){            if(matrix[i][0]==0){                isFirstColZero=true;                break;            }        }        for(i=0;i<n;i++){            if(matrix[0][i]==0){                isFirstRowZero=true;                break;            }                    }                for(i=0;i<m;i++){            for(j=0;j<n;j++){                if(matrix[i][j]==0){                    matrix[0][j]=0;                    matrix[i][0]=0;                }                            }                    }                for(i=1;i<m;i++){            if(matrix[i][0]==0){                for(j=0;j<n;j++)                    matrix[i][j]=0;            }                    }                for(i=1;i<n;i++){            if(matrix[0][i]==0){                for(j=0;j<m;j++)                    matrix[j][i]=0;            }        }                if(isFirstRowZero){            for(i=0;i<n;i++)                matrix[0][i]=0;        }                if(isFirstColZero){            for(i=0;i<m;i++)                matrix[i][0]=0;        }                return;            }}
View Code

 

参考:

http://jane4532.blogspot.com/2013/09/set-matrix-zeroleetcode.html