题解 | #机器人的运动范围#

机器人的运动范围

https://www.nowcoder.com/practice/6e5207314b5241fb83f2329e89fdecc8?tpId=265&tqId=39217&rp=1&ru=/exam/oj/ta&qru=/exam/oj/ta&sourceUrl=%2Fexam%2Foj%2Fta%3FjudgeStatus%3D3%26page%3D1%26pageSize%3D50%26search%3D%26tpId%3D13%26type%3D265&difficulty=undefined&judgeStatus=3&tags=&title=

一开始想错了,机器人只能从一个点进入,不可以随机挑选点进入

class Solution {
  public:
    int movingCount(int threshold, int rows, int cols) {
      int res = 0;
      std::vector<std::vector<int>> matrix(rows, std::vector<int>(cols, 0));
      
      for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
          matrix[i][j] = i % 10 + i / 10 + j % 10 + j / 10;
        }
      }
      
     //  只能从一个起点开始探索
     dfs(matrix, threshold, rows, cols, 0, 0, res);
      
      return res;
    }
  private:
    void dfs(std::vector<std::vector<int>> &matrix, const int &threshold, const int &rows, const int &cols, int i, int j, int &res) {
      if (i >= rows || i < 0 || j >= cols || j < 0 || matrix[i][j] == -1 || matrix[i][j] > threshold) {
        return ;
      }
      
      ++res;
      matrix[i][j] = -1;
      
      dfs(matrix, threshold, rows, cols, i + 1, j, res);
      dfs(matrix, threshold, rows, cols, i - 1, j, res);
      dfs(matrix, threshold, rows, cols, i, j + 1, res);
      dfs(matrix, threshold, rows, cols, i, j - 1, res);
    }
};
全部评论

相关推荐

12-24 14:26
东北大学 Java
一只乌鸦:重邮+东北,好经典的学校
最后再改一次简历
点赞 评论 收藏
分享
12-13 14:51
已编辑
井冈山大学 算法工程师
龙虾x:算法比你强的没有你美,比你美的…..算了已经没有比你美的了
工作两年想退休了
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务