演算法Set Matrix Zeroes

dongyu2013發表於2014-05-04

點選(此處)摺疊或開啟

  1. public class Solution {
  2.     public void setZeroes(int[][] matrix) {
  3.         boolean firstRowZero = false;
  4.         boolean firstColumnZero = false;
  5.  
  6.         //set first row and column zero or not
  7.         for(int i=0; i<matrix.length; i++){
  8.             if(matrix[i][0] == 0){
  9.                 firstColumnZero = true;
  10.                 break;
  11.             }
  12.         }
  13.  
  14.         for(int i=0; i<matrix[0].length; i++){
  15.             if(matrix[0][i] == 0){
  16.                 firstRowZero = true;
  17.                 break;
  18.             }
  19.         }
  20.  
  21.         //mark zeros on first row and column
  22.         for(int i=1; i<matrix.length; i++){
  23.             for(int j=1; j<matrix[0].length; j++){
  24.                 if(matrix[i][j] == 0){
  25.                    matrix[i][0] = 0;
  26.                    matrix[0][j] = 0;
  27.                 }
  28.             }
  29.         }
  30.  
  31.         //use mark to set elements
  32.         for(int i=1; i<matrix.length; i++){
  33.             for(int j=1; j<matrix[0].length; j++){
  34.                 if(matrix[i][0] == 0 || matrix[0][j] == 0){
  35.                    matrix[i][j] = 0;
  36.                 }
  37.             }
  38.         }
  39.  
  40.         //set first column and row
  41.         if(firstColumnZero){
  42.             for(int i=0; i<matrix.length; i++)
  43.                 matrix[i][0] = 0;
  44.         }
  45.  
  46.         if(firstRowZero){
  47.             for(int i=0; i<matrix[0].length; i++)
  48.                 matrix[0][i] = 0;
  49.         }
  50.  
  51.     }
  52. }

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29012686/viewspace-1153244/,如需轉載,請註明出處,否則將追究法律責任。

相關文章