思路
能用深搜就用深搜,代码简洁明了
宽搜比较繁琐
算法一:深搜
写法一:
private static int[] dx={0,0,-1,1},dy={1,-1,0,0};
private static String[] str;
private static boolean[][] st;
private static int w,h,sum;
public static int dfs(int a,int b){//返回的是瓷砖数
st[a][b]=true;
int cnt=1;
for(int i=0;i<4;i++){
int x=a+dx[i],y=b+dy[i];//这里要注意是新的变量,不能是a=a+dx[i]
if(x>=h||x<0||y>=w||y<0)continue;//下标越界
if(str[x].charAt(y)=='#')continue;//是墙壁
if(st[x][y])continue;//已经走过了
cnt+=dfs(x,y);
}
return cnt;
}
public static void main(String[] args){
Scanner scanner=new Scanner(System.in);
w=scanner.nextInt();h=scanner.nextInt();
int N=25;
while(w!=0&&h!=0){
str=new String[N];
st=new boolean[N][N];
int x=0,y=0;
for(int i=0;i<h;i++){
str[i]=scanner.next();
if(str[i].indexOf('@')>=0){
x=i;y=str[i].indexOf('@');
}
}
System.out.println(dfs(x,y));
w=scanner.nextInt();h=scanner.nextInt();
}
}
写法二:
private static int[] dx={0,0,-1,1},dy={1,-1,0,0};
private static String[] str;
private static boolean[][] st;
private static int w,h,sum;
public static void dfs(int a,int b){
if(a<0||a>=h||b<0||b>=w||st[a][b]||str[a].charAt(b)=='#'){//若不满足情况则结束递归
return ;
}
st[a][b]=true;//说明该点走过
sum++;//瓷砖数加一
for(int i=0;i<4;i++){
int x=a+dx[i];
int y=b+dy[i];
dfs(x,y);
}
}
public static void main(String[] args){
Scanner scanner=new Scanner(System.in);
w=scanner.nextInt();h=scanner.nextInt();
while(w!=0&&h!=0){
str=new String[100];
st=new boolean[100][100];
int sx=0,sy=0;
for(int i=0;i<h;i++){
str[i]=scanner.next();
if(str[i].indexOf('@')!=-1){
sx=i;
sy=str[i].indexOf('@');
}
}
sum=0;//每次都要初始化
dfs(sx,sy);
System.out.println(sum);
w=scanner.nextInt();h=scanner.nextInt();
}
}
算法二:广搜
套用广搜模板即可
class Node{
int x;
int y;
public Node(int x,int y){
this.x=x;
this.y=y;
}
public int getX(){return x;}
public int getY(){return y;}
}
class Main{
public static void main(String[] args){
Scanner scanner=new Scanner(System.in);
int h=scanner.nextInt(),w=scanner.nextInt();
int[] dx={0,0,-1,1},dy={1,-1,0,0};
while(w!=0&&h!=0){
String[] str=new String[100];
boolean[][] st=new boolean[100][100];
int sx=0,sy=0;
for(int i=0;i<w;i++){
str[i]=scanner.next();
if(str[i].indexOf('@')!=-1){
sx=i;
sy=str[i].indexOf('@');
}
}
Queue<Node> queue=new LinkedList<>();
queue.add(new Node(sx,sy));
st[sx][sy]=true;
int sum=1;
while(!queue.isEmpty()){
Node node=queue.poll();
for(int i=0;i<4;i++){
int x=node.x+dx[i];
int y=node.y+dy[i];
if(x>=0&&x<w&&y>=0&&y<h&&str[x].charAt(y)!='#'&&!st[x][y]){
queue.add(new Node(x,y));
st[x][y]=true;
sum++;
}
}
}
System.out.println(sum);
h=scanner.nextInt();w=scanner.nextInt();
}
}
}