1. 程式人生 > >【LeetCode & 劍指offer刷題】回溯法與暴力列舉法題3:13 機器人的運動範圍

【LeetCode & 劍指offer刷題】回溯法與暴力列舉法題3:13 機器人的運動範圍

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

13 機器人的運動範圍

題目描述

地上有一個m行和n列的方格。一個機器人 從座標0,0的格子開始移動,每一次只能向左,右,上,下四個方向移動一格,但是 不能進入行座標和列座標的數位之和大於k的格子。 例如,當k為18時,機器人能夠進入方格(35,37),因為3+5+3+7 = 18。但是,它不能進入方格(35,38),因為3+5+3+8 = 19。 請問該機器人能夠達到多少個格子?   // 方法一:暴力法列舉,練成路徑
// 方法二:回溯法,試探的走,如果不滿足條件或越界則回溯 class Solution { public :     int movingCount ( int threshold , int rows , int cols )     {
      //  vector<bool> visited(rows*cols,false); // 建立訪問陣列                 //也可用(vector<vector<bool> > visited(m, vector<bool>(n, false)); //建立訪問矩陣        
bool * visited = new bool [ rows * cols ]; // 建立訪問陣列         for ( int i = 0 ; i < rows * cols ; i ++) visited [ i ] = false ;         int count = helper ( 0 , 0 , rows , cols , visited , threshold );                 delete [] visited ; // 釋放記憶體         return count ;     } private :     int helper ( int i , int j , int rows, int cols , bool * visited , int threshold )     {         bool temp1 = i < 0 || i >= rows || j < 0 || j >= cols ;         bool temp2 = ( numSum ( i ) + numSum ( j )) > threshold ;         if ( visited[cols*i + j] || temp1 || temp2 ) return 0 ; //如果已經訪問過或越界或者不滿足約束條件,則不走這個格子,回溯         else visited [ cols * i + j ] = true ;                 return helper ( i - 1 , j , rows , cols , visited , threshold )             + helper ( i + 1 , j , rows , cols , visited , threshold )             + helper ( i , j - 1 , rows , cols , visited , threshold )             + helper ( i , j + 1 , rows , cols , visited , threshold )             + 1 ; //遞迴統計所能走的格子數     }     int numSum ( int num ) //進行某數的數位相加     {         int sum = 0 ;         while ( num > 0 )         {             sum += num % 10 ;             num /= 10 ;         }         return sum ;     } };