13. 机器人的运动范围

class Solution {
public:
    int cnt=0;
    int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
    bool st[55][55];
    void dfs(int x,int y,int k,int rows, int cols)
    {
        if(x<0||x>=rows||y<0||y>=cols)  return;
        //判断数位之和是否满足条件
        int t=0,x1=x,y1=y;
        while(x1)
        {
            t+=x1%10;
            x1/=10;
        }
        while(y1)
        {
            t+=y1%10;
            y1/=10;
        }
        if(t>k) return;
        if(st[x][y])    return;
        st[x][y]=true;
        for (int i = 0; i < 4; i ++ )
        {
            int a=dx[i]+x,b=dy[i]+y;
            dfs(a,b,k,rows,cols);
        }
    }
    int movingCount(int threshold, int rows, int cols)
    {
        dfs(0,0,threshold,rows,cols);
        for (int i = 0; i < rows; i ++ )
            for (int j = 0; j < cols; j ++ )
                if(st[i][j])    cnt++;
        return cnt;
    }
};
posted @ 2023-03-18 10:36  穿过雾的阴霾  阅读(15)  评论(0)    收藏  举报