简单的一道广搜题,我看大部分题解都是用二维数组来标记是否点被访问过,可能会造成空间浪费,用HashMap以String作为key的方法来解一下。
import java.util.*;
class Node{
int x,y;
Node(int x,int y){
this.x=x;
this.y=y;
}
}
public class Solution {
static HashMap<String,Boolean>map;
static Queue<Node>queue=new LinkedList<>();
static int xMove[]={1,0,-1,0};
static int yMove[]={0,1,0,-1};
static boolean isTrue(int x,int y,int threshold){//不能进入行坐标和列坐标的数位之和大于k的格子
int sum=0;
while (x>0){
sum+=(x%10);
x/=10;
}
while (y>0){
sum+=(y%10);
y/=10;
}
if(sum>threshold)
return false;
return true;
}
/* @Test
public void test(){
Scanner scanner=new Scanner(System.in);
*//*int threshold=scanner.nextInt();
int rows=scanner.nextInt();
int cols=scanner.nextInt();*//*
System.out.print(movingCount(10,30,30));
}*/
public static int movingCount(int threshold, int rows, int cols){
int sum=0;
StringBuilder stringBuilder=new StringBuilder();
if(threshold<0)
return 0;
map=new HashMap<>();
map.clear();
stringBuilder.append(0);
stringBuilder.append(',');
stringBuilder.append(0);
String s;
s=stringBuilder.toString();
sum++;
map.put(s,true);
Node node=new Node(0,0);
queue.offer(node);
while (queue.isEmpty()==false){
Node nodePoll=queue.poll();
for(int i=0;i<4;i++){
int x=nodePoll.x+xMove[i];
int y=nodePoll.y+yMove[i];
if(x>=0&&y>=0&&x<rows&&y<cols&&isTrue(x,y,threshold)){
stringBuilder.setLength(0);
stringBuilder.append(x);
stringBuilder.append(',');
stringBuilder.append(y);
s=stringBuilder.toString();
if(map.get(s)==null){
Node nodeNew=new Node(x,y);
queue.offer(nodeNew);
sum++;
map.put(s,true);
}
}
}
}
// stringBuilder.setLength(0);
return sum;
}
}