题目描述
有一间长方形的房子,地上铺了红色、黑色两种颜色的正方形瓷砖。
你站在其中一块黑色的瓷砖上,只能向相邻(上下左右四个方向)的黑色瓷砖移动。
请写一个程序,计算你总共能够到达多少块黑色的瓷砖。
输入格式
输入包括多个数据集合。
每个数据集合的第一行是两个整数 W W W 和 H H H,分别表示 x x x 方向和 y y y 方向瓷砖的数量。
在接下来的 H H H 行中,每行包括 W W W 个字符。每个字符表示一块瓷砖的颜色,规则如下
1)‘.’:黑色的瓷砖;
2)‘#’:红色的瓷砖;
3)‘@’:黑色的瓷砖,并且你站在这块瓷砖上。该字符在每个数据集合中唯一出现一次。
当在一行中读入的是两个零时,表示输入结束。
输出格式
对每个数据集合,分别输出一行,显示你从初始位置出发能到达的瓷砖数(记数时包括初始位置的瓷砖)。
数据范围
1 ≤ W , H ≤ 20 1≤W,H≤20 1≤W,H≤20
输入样例:
6 9
....#.
.....#
......
......
......
......
......
#@...#
.#..#.
0 0
输出样例:
45
BFS代码
import java.util.*;
class Main
{
public static class Point
{
int x; //这里不能是static int,否则x的值会变
int y;
public Point(int x,int y)
{
this.x=x;
this.y=y;
}
}
public static int N=25;
public static char[][] map = new char[N][N];
public static int w,h;
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
while(true)
{
w=sc.nextInt();
h=sc.nextInt();
if(w==0 && h==0) break;
Point start = new Point(-1,-1); //定义起点
for(int i=0;i<h;i++)
{
map[i]=sc.next().toCharArray();
for(int j=0;j<w;j++)
{
if(map[i][j]=='@')
{
start = new Point(i,j); //得到起点
}
}
}
System.out.println(bfs(start)); //宽搜
}
}
public static int bfs(Point start)
{
Queue<Point> queue = new LinkedList<>();
queue.add(start);
int cnt=0;
int dx[] = {1,-1,0,0}; //四个方向
int dy[] = {0,0,1,-1};
boolean[][] isVisited = new boolean[N][N]; //记录是否走过
while(!queue.isEmpty())
{
Point newPoint = queue.poll();
for(int i=0;i<4;i++)
{
int x=newPoint.x+dx[i];
int y=newPoint.y+dy[i];
if(x>=0 && x<h && y>=0 && y<w && map[x][y]=='.' && !isVisited[x][y]) //如果能走
{
isVisited[x][y]=true;
cnt++;
queue.add(new Point(x,y));
}
}
}
return cnt+1;
}
}
DFS代码
import java.util.*;
class Main
{
public static int N=25;
public static char[][] map = new char[N][N];
public static int w,h;
public static int dx[] = {1,-1,0,0}; //四个方向
public static int dy[] = {0,0,1,-1};
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
while(true)
{
w=sc.nextInt();
h=sc.nextInt();
if(w==0 && h==0) break;
int x=-1,y=-1; //定义起点
for(int i=0;i<h;i++)
{
map[i]=sc.next().toCharArray();
for(int j=0;j<w;j++)
{
if(map[i][j]=='@')
{
x=i;
y=j; //得到起点
}
}
}
System.out.println(dfs(x,y)); //深搜
}
}
public static int dfs(int x,int y)
{
map[x][y]='#'; //变成不能走的红色
int cnt=1;
for(int i=0;i<4;i++)
{
int xt=x+dx[i];
int yt=y+dy[i];
if(xt>=0 && xt<h && yt>=0 && yt<w && map[xt][yt]=='.') //如果能走
{
cnt+=dfs(xt,yt);
}
}
return cnt;
}
}