troubleasy

导航

 

题目描述

地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
    int movingCount(int threshold, int rows, int cols)
    {
        vector<vector<int> >res(rows);
        for(int i=0;i<rows;i++)
        {
            res[i].resize(cols);
        }
        for(int i=0;i<rows;i++)
            for(int j=0;j<cols;j++)
            {
                res[i][j]=0;
            }
        //仅沿着能进入方格的路径走
        return reach(res,threshold,rows,cols,0,0);
    }
    int reach(vector<vector<int> >&mesh,int th,int rows,int cols,int r,int c)
    {

        if((r>=0)&&(c>=0)&&(r<=rows-1)&&(c<=cols-1))
        {
           int t=0;
           int i=r,j=c;
           while(i)
          {
              t+=i%10;
              i/=10;
          }
        while(j)
        {
            t+=j%10;
            j/=10;
        }
            if(mesh[r][c]==0&&t<=th)
            {
                mesh[r][c]=1;
                return 1+reach(mesh,th,rows,cols,r-1,c)+reach(mesh,th,rows,cols,r+1,c)+reach(mesh,th,rows,cols,r,c-1)+reach(mesh,th,rows,cols,r,c+1);
            }
        }
        return 0;
    }
posted on 2020-05-29 17:56  troubleasy  阅读(85)  评论(0编辑  收藏  举报