首页 > 学院 > 开发设计 > 正文

机器人的运动范围

2019-11-08 01:23:49
字体:
来源:转载
供稿:网友

地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?

直接用bfs从(0,0)位置开始搜索

import java.util.LinkedList ; import java.util.Queue ; public class Solution {    PRivate boolean judge(int threshold , int x , int y){        int num = 0 ;         while(x > 0){            num += (x%10) ;             x/=10 ;         }        while(y > 0){            num += (y%10) ;             y/=10 ;         }        return num > threshold ;     }    public int movingCount(int threshold, int rows, int cols){        Queue que = new LinkedList() ;         boolean[][] vis = new boolean[rows][cols] ;         que.add(0) ;         que.add(0) ;         int[] dx = {0 , 0 , 1 , -1} ;         int[] dy = {1 , -1 , 0 , 0} ;         int ans = 0 ;         while(que.size() > 0){            int x = que.poll() ;             int y = que.poll() ;             if(x < 0 || x >= rows || y < 0 || y >= cols || vis[x][y] || judge(threshold,x,y)){                continue ;             }            ans++ ;             vis[x][y] = true ;             for(int i = 0;i < 4;i++){                int nx = x + dx[i] ;                 int ny = y + dy[i] ;                 que.add(nx) ;                 que.add(ny) ;             }        }        return ans ;     }}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表