BFS搜索题目。
import java.util.Scanner;public class Main {
//定义全局变量static int[][] dir = {
{
0,1},{
1,0},{
-1,0},{
0,-1}}; //定义行走的方向上下左右static int cnt = 0; //计数格子static int w ;static int h ;public static void main(String[] args) {
Scanner sc = new Scanner(System.in);while(sc.hasNext()){
w = sc.nextInt();h = sc.nextInt();//等于0时输入结束if(w == 0 && h == 0) break;boolean[][] isVisited = new boolean[h+1][w+1];//标志是否被访问过的数组String[] s = new String[h+1];for (int i = 1; i <= h; i++) {
s[i] = sc.next();//字符串数组接收每一行字符串}//数组存图char[][] tu = new char[h+1][w+1];for (int i = 1; i <= h; i++) {
int n = 0;for (int j = 1; j <= w; j++) {
tu[i][j] = s[i].charAt(n);//字符串数组转字符二维数组n++;}}//遍历寻找出发点,记下初始坐标int indexX = 0;int indexY = 0;for (int i = 1; i <= h; i++) {
for (int j = 1; j <= w; j++) {
if(tu[i][j] == '@') {
indexX = i;indexY = j;}}}bfs(indexX,indexY,tu,isVisited);//bfs函数递归遍历搜索System.out.println(cnt+1); //因为自身站的地方也算一块,所以要再加一块cnt = 0;}}//bfspublic static void bfs(int x,int y,char[][] tu,boolean[][] isVisited){
int dx;int dy;for (int i = 0; i < 4; i++) {
//每一次进bfs方法也就是每一次坐标移动都会含有四个方向的循环遍历,所以是肯定能遍历完全图的dx = x +dir[i][0];dy = y + dir[i][1];if(dx>=1 && dx<=h && dy>=1 && dy <= w && tu[dx][dy] == '.' && !isVisited[dx][dy]){
isVisited[dx][dy] = true;cnt++;bfs(dx,dy,tu,isVisited);}}}
}