ロボットの動きの範囲 - 牛オフ

タイトル説明は
m行n列のグリッドが存在するグランド。0,0グリッド座標からロボットが移動し、毎回四方セルを上下、左右が、グリッドの行および列の座標を入力することができないだけではビットkの数の合計よりも大きいです。kが18である場合、例えば、ロボットが3 + 3 + 5 + 7 = 18から、ボックス(35、37)を入力することができます。3 + 3 + 5 + 8 = 19しかし、それは、ボックス(35、38)を入力することができません。ロボットは、格子の数に到達することができるだろうか?
ソリューション:
1、深さ優先探索
2、四方
の質問に似て3、

class Solution {
public:
    int sum(int num)
    {
        int s = 0;
        while(num)
        {
            s += num%10;
            num /= 10;
        }
        return s;
    }
    int DFS(int threshold, int r, int c, int rows, int cols, bool*vis)
    {
        int cnt = 0;
        if(r>=0 && r<rows && c>=0 && c<cols && (sum(r)+sum(c)) <= threshold && !vis[r*cols+c])
        {
            vis[r*cols+c] = 1;
            cnt = 1 + DFS(threshold, r+1, c, rows, cols, vis)
                + DFS(threshold, r-1, c, rows, cols, vis)
                + DFS(threshold, r, c+1, rows, cols, vis)
                + DFS(threshold, r, c-1, rows, cols, vis);
        }
        return cnt;
    }
    int movingCount(int threshold, int rows, int cols)
    {
        bool* vis = new bool[rows*cols];
        memset(vis, 0, rows*cols);
        int cnt = DFS(threshold, 0, 0, rows, cols, vis);
        return cnt;
    }
};
公開された315元の記事 ウォンの賞賛119 ビュー110 000 +

おすすめ

転載: blog.csdn.net/w144215160044/article/details/105056226