地上有一个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){ Queueque = 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 ; }}
新闻热点
疑难解答