方法一 DFS(深度优先搜素)
import java.io.*; import java.util.*; public class Main { int M=22,w,h,sx,sy; char ch[][]; int fx[]={1,-1,0,0}; int fy[]={0,0,1,-1}; int number; boolean boo[][]=new boolean[100][100]; public static void main(String[] args) { new Main().work(); } void work(){ Scanner sc=new Scanner(new BufferedInputStream(System.in)); while(sc.hasNext()){ w=sc.nextInt(); h=sc.nextInt(); if(h==0&&w==0) System.exit(0); ch=new char[h][w]; for(int i=0;i<h;i++){ String s=sc.next(); ch[i]=s.toCharArray(); Arrays.fill(boo[i], false); } for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ if(ch[i][j]=='@'){ sx=i; sy=j; } } } number=1; boo[sx][sy]=true; DFS(sx,sy); System.out.println(number); } } void DFS(int sx,int sy){ for(int i=0;i<4;i++){ int px=sx+fx[i]; int py=sy+fy[i]; if(check(px,py)&&!boo[px][py]){ number++; boo[px][py]=true; DFS(px,py); } } } boolean check(int px,int py){ if(px<0||px>h-1||py<0||py>w-1||ch[px][py]!='.') return false; return true; } }
方法二 BFS( 广度优先搜索)
import java.io.*; import java.util.*; public class Main { Queue<Node> que = new LinkedList<Node>(); boolean boo[][] = new boolean[100][100]; char ch[][]; int w, h; int fx[] = { 1, -1, 0, 0 }; int fy[] = { 0, 0, 1, -1 }; int number; public static void main(String[] args) { new Main().work(); } void work() { Scanner sc = new Scanner(new BufferedInputStream(System.in)); while (sc.hasNext()) { w = sc.nextInt(); h = sc.nextInt(); if(h==0&&w==0) System.exit(0); ch = new char[h][w]; for (int i = 0; i < h; i++) { String s = sc.next(); ch[i] = s.toCharArray(); Arrays.fill(boo[i], false); } Node node = new Node(); for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { if (ch[i][j] == '@') { node.x = i; node.y = j; node.number = 1; } } } boo[node.x][node.y] = true; que.add(node); number = 1; BFS(); System.out.println(number); } } void BFS() { while (!que.isEmpty()) { Node node = que.poll(); for (int i = 0; i < 4; i++) { int px = node.x + fx[i]; int py = node.y + fy[i]; if (check(px, py) && !boo[px][py]) { number++; Node td = new Node(); td.x = px; td.y = py; boo[px][py] = true; ch[px][py] = 'S'; que.add(td); } } } } boolean check(int px, int py) { if (px < 0 || px > h - 1 || py < 0 || py > w - 1 || ch[px][py] != '.') return false; return true; } class Node { int x; int y; int number; } }