1. 程式人生 > >【LeetCode & 劍指offer刷題】矩陣題4:Set Matrix Zeroes

【LeetCode & 劍指offer刷題】矩陣題4:Set Matrix Zeroes

【LeetCode & 劍指offer 刷題筆記】目錄(持續更新中...)

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 . Example 1: Input:
[ [1,1,1], [1,0,1], [1,1,1] ] Output: [ [1,0,1], [0,0,0], [1,0,1] ] Example 2:
Input: [ [0,1,2,0], [3,4,5,2], [1,3,1,5] ] Output: [ [0,0,0,0], [0,4,5,0], [0,3,1,0] ]
Follow up:
  • A straight forward solution using O( m n ) 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?

C++   //將矩陣中為0的元素其整行整列均置為0,要求in-place解決 //方法:第一次掃描,用首行首列儲存狀態,第二次掃描,根據這些狀態把相應位置置0 //O(mn),O(1) class Solution { public :     void setZeroes ( vector < vector < int >>& a )     {         int rows = a . size ();         int cols = a [ 0 ]. size ();         bool fr = false ; //用於表示首行是否存在0元素的標識變數         bool fc = false ;                 for ( int i = 0 ; i < rows ; i ++)         {             for ( int j = 0 ; j < cols ; j ++)             {                 if ( a [ i ][ j ] == 0 )                 {                     a [ i ][ 0 ] = a [ 0 ][ j ] = 0 ; //當某個元素為0時,將行首和列首元素置0                     if ( i == 0 ) fr = true ; //第一行有0元素                     if ( j == 0 ) fc = true ; //第一列有0元素                 }             }         }                 for ( int i = 1 ; i < rows ; i ++) //從a11開始掃描,以免破壞首行首列儲存資訊         {             for ( int j = 1 ; j < cols ; j ++)             {                 if ( a [ i ][ 0 ] == 0 || a [ 0 ][ j ] == 0 ) a [ i ][ j ] = 0 ;             }         }                 if ( fr )         {             for ( int j = 0 ; j < cols ; j ++) a [ 0 ][ j ] = 0 ; //將第一行置0         }         if ( fc )         {             for ( int i = 0 ; i < rows ; i ++) a [ i ][ 0 ] = 0 ; //將第一列置0         }             } };