题目链接点击这里Red and Black
使用方法:递归的深度优先遍历和非递归的深度优先遍历两种实现方式
代码:
import java.io.*;
import java.util.Stack;
import java.util.Scanner;
public class Main {
private static Scanner in = new Scanner(System.in);
private static char [][]matrix;
private static int sum;
private static int w;
private static int h;
private static int []a = {1,-1,0,0};
private static int []b = {0,0,-1,1};
private static boolean isLegal(int x,int y){
if(x<0 || x>=h || y<0 || y>=w) return false;
return true;
}
// 递归的dfs
// private static void dfs(int x,int y){
// if(matrix[x][y]=='.') {
// sum++;
// matrix[x][y] = '*';
// }
// for(int i=0;i<4;i++)
// {
// int dx = x + a[i];
// int dy = y + b[i];
// if(judge(dx,dy) && matrix[dx][dy]=='.'){
// dfs(dx,dy);
// }
// }
// }
private static class Point{
int x,y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
}
//非递归的dfs
private static void dfs(int x , int y){
Stack<Point> stack = new Stack<>();
stack.add(new Point(x,y));
while(!stack.isEmpty()){
Point p = stack.pop();
x = p.x;
y = p.y;
if(matrix[x][y]=='.'){
sum++;
matrix[x][y] = '*';
}
for(int i=0; i<4; i++)
{
int dx = x + a[i];
int dy = y + b[i];
if(isLegal(dx,dy)){
if(matrix[dx][dy]=='.'){
stack.push(new Point(dx,dy));
}
}
}
}
}
public static void main(String[] args) throws IOException{
w = in.nextInt();
h = in.nextInt();
String str;
int x=0,y=0;
while(w!=0 || h!=0){
matrix = new char[h][w];
for(int i=0;i<h;i++)
{
str = in.next();
for(int j=0;j<w;j++)
{
matrix[i][j] = str.charAt(j);
if(matrix[i][j]=='@'){
x = i;
y = j;
}
}
}
sum = 0;
dfs(x,y);
System.out.println(sum+1);
w = in.nextInt();
h = in.nextInt();
}
}
}