計算機器人走的範圍

題目描述

地上有一個m行和n列的方格。一個機器人從座標0,0的格子開始移動,每一次只能向左,右,上,下四個方向移動一格,但是不能進入行座標和列座標的數位之和大於k的格子。 例如,當k爲18時,機器人能夠進入方格(35,37),因爲3+5+3+7 = 18。但是,它不能進入方格(35,38),因爲3+5+3+8 = 19。請問該機器人能夠達到多少個格子?

 

#include  <iostream>
#include  <vector>
using namespace std;

#if 0
bool  isPath(char *matrix,vector<char> flags,char* str,int x,int y,int rows,int cols)
{
    if(x<0||y<0||x>rows||y>cols) return false;
    if(matrix[x*cols+y]==*str&&flags.at(x*cols+y)==0){
        flags.at(x*cols+y)=1;
        if(*(str+1)=='\0'){
            return true;
        }
        bool condition=isPath(matrix,flags,(str+1),x,y-1,rows,cols)||
                isPath(matrix,flags,(str+1),x,y+1,rows,cols)||
                isPath(matrix,flags,(str+1),x-1,y,rows,cols)||
                isPath(matrix,flags,(str+1),x+1,y,rows,cols);
        if(condition==false){
            flags.at(x*cols+y)=false;
        }
        return condition;

    }else{
        return false;
    }
}
#endif
int getsum(int num)
{
  int  sum=0;
  while(num){
    sum+=num%10;
    num/=10;
  }
  return sum;
}
int moving(int threshold,int rows,int cols,int i,int j,bool* flag)
{
  int  count=0;
  if(i>=0&&i<rows&&j>=0&&j<cols&&flag[i*cols+j]==false&&((getsum(i)+getsum(j))<=threshold)){
   flag[i*cols+j]=true;
   count=1+moving(threshold,rows,cols,i,j-1,flag)+
           moving(threshold,rows,cols,i+1,j,flag)+
           moving(threshold,rows,cols,i-1,j,flag)+
           moving(threshold,rows,cols,i,j+1,flag);
  }
  return count;
}
int movingCount(int threshold,int rows,int cols)
{
    bool *flag=new bool[rows*cols];
    for(int i=0;i<rows*cols;i++)
    {
       flag[i]=false; //intial
    }
    int count=moving(threshold,rows,cols,0,0,flag);
    return count;

}
#if 0
bool  haspath(char* matrix,int rows,int cols,char *str)
{
    vector<char> flags(rows*cols,0);
    bool condition=false;
    for(int i=0;i<rows;i++){
        for(int j=0;j<cols;j++){
            condition=(condition||isPath(matrix,flags,str,i,j,rows,cols));
        }
    }
    return condition;
}
#endif
int main(int argc,char * argv[])
{
#if 0
    char* str="abcesfcsadee";
    char* str1="abcb";
    bool res=haspath(str,3,4,str1);
    cout<<res;
#endif
  int ress=movingCount(18,35,40);
  cout<<ress;

    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章