題目描述
地上有一個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 count=0;int numSum(int num) { int rev=0; while(num) { rev+=num%10; num=num/10; } return rev; } void fun(int x,int y,int threshold,int rows,int cols,bool * flags) { if(x<0||y<0||x>=rows||y>=cols||flags[x*cols+y]) return; if(flags[x*cols+y]==false&&(numSum(x)+numSum(y)<=threshold) ) { flags[x*cols+y]=true; count++; fun(x+1,y,threshold,rows,cols,flags); fun(x-1,y,threshold,rows,cols,flags); fun(x,y+1,threshold,rows,cols,flags); fun(x,y-1,threshold,rows,cols,flags); } } int movingCount(int threshold, int rows, int cols) { bool * flags=new bool[rows*cols]; for(int i=0;i<rows;i++) { for(int j=0;j<cols;j++) flags[i*cols+j]=false; } fun(0,0,threshold,rows,cols,flags); return count; }};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/24581.html
標籤:其他
上一篇:Julia 入門學習教程
下一篇:矩陣中的路徑
