剑指offer67题-No66.机器人的运动范围

和NO65差不多,dfs即可。

#include <vector>
using namespace std;

class Solution {
public:
    int dx[4] = {1,0,-1,0};
    int dy[4] = {0,1,0,-1};
    int row;
    int col;
    int count; 
    int t;

    int movingCount(int threshold, int rows, int cols) {
        if(rows <=0 || cols <=0) return 0;
        row = rows;
        col = cols;
        t = threshold;
        count = 0; 
        vector<vector<bool>> visited(row, vector<bool>(col, false));
        dfs(0, 0, visited);
        return count;
    }

    void dfs(int i, int j, vector<vector<bool>>& v){
        // 检查坐标合法性、是否已访问及数位和条件
        if(i < 0 || i >= row || j < 0 || j >= col || v[i][j] || cal(i, j) > t)
            return;
        
        v[i][j] = true;  // 标记当前格子为已访问
        count++;         // 增加可达格子数
        
        // 向四个方向继续搜索
        for(int l = 0; l < 4; l++){
            int curx = dx[l] + i;
            int cury = dy[l] + j;
            dfs(curx, cury, v);
        }
    }

    int cal(int x, int y){
        int res = 0;
        while(x != 0){
            res += x % 10;
            x /= 10;
        }
        while(y != 0){
            res += y % 10;
            y /= 10;
        }
        return res;
    }
};
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇