剑指offer-13 机器人运动范围

剑指offer-13 机器人运动范围

广度优先BFS

只用向下或向右

[0, 0]先入队列,

当队列不为空,shift出一个坐标。如果当前坐标满足条件,则将左右节点入队列,同时标记该节点,同时结果+1;若不满足条件,则什么都不做,跳过这轮循环。

其实跟树的遍历差不多嘛(简化条件后)

 

 

【麻了】

代码:

var movingCount = function(m, n, k) {
   const getSum = function(x, y){
       let res = 0;
       while(x > 0){
           res += Math.floor(x % 10);
           x /= 10;
      }
       while(y > 0){
           res += Math.floor(y % 10);
           y /= 10;
      }
       return res;
  }
   let queue = [];
   let visited = {};
   let res = 0;
   if(m === 0 || n === 0) return 0;
   queue.push([0, 0]);
   while(queue.length > 0){
       let node = queue.shift();
       if(node[0] > m-1 || node[1] > n-1 || visited[`${node[0]}-${node[1]}`] || getSum(node[0], node[1]) > k)
           continue;
       queue.push([node[0]+1, node[1]]);
       queue.push([node[0], node[1]+1]);
       visited[`${node[0]}-${node[1]}`] = true;
       res ++ ;
  }
   return res;
};

 

posted @ 2021-01-31 16:51  团叽  阅读(61)  评论(0编辑  收藏  举报