算法1 BFS
package dbfs;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
class Pair{
int x;
int y;
public Pair(int x, int y) {
super();
this.x = x;
this.y = y;
}
}
public class 红与黑 {
/**
* bfs
* @param args
* @throws IOException
*/
static int N=30;
static int w,h;
static boolean st[][];
static char g[][]=new char [N][N];
static int res;
static int stx=0;
static int sty=0;
static int dx[]={-1,0,0,1};
static int dy[]={0,1,-1,0};
public static void bfs() {
res=1;
Queue<Pair> queue= new LinkedList<Pair>();
st[stx][sty]=true;
queue.offer(new Pair(stx, sty));
while(!queue.isEmpty()){
Pair pair1= queue.poll();
for(int i=0;i<4;i++){
int x=pair1.x+dx[i];
int y=pair1.y+dy[i];
if(x>=0 && x<h && y>=0 && y<w && !st[x][y] && g[x][y]=='.'){
queue.offer(new Pair(x, y));
st[x][y]=true;
res++;
}
}
}
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
while(true){
String p[]=bufferedReader.readLine().split(" ");
w=Integer.parseInt(p[0]);//列
h=Integer.parseInt(p[1]);//行
if(w==0 && h==0) break;
for(int i=0;i<h;i++){
String s=bufferedReader.readLine();
for(int j=0;j<w;j++){
char o=s.charAt(j);
if(o=='@'){
stx=i;
sty=j;
}
g[i][j]=o;
}
}
st=new boolean[N][N];
bfs();
System.out.println(res);
}
}
}
算法2
dfs
package dbfs;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class 红与黑dfs {
/**
* @param args
*/
static int N=30;
static int w,h;
static boolean st[][];
static char g[][]=new char [N][N];
static int res;
static int stx=0;
static int sty=0;
static int dx[]={-1,0,0,1};
static int dy[]={0,1,-1,0};
public static void dfs(int stax,int stay) {
for(int i=0;i<4;i++){
int x=stax+dx[i];
int y=stay+dy[i];
if(x>=0 && x<h && y>=0 && y<w && !st[x][y] && g[x][y]=='.'){
st[x][y]=true;
res++;
dfs(x, y);
}
}
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
while(true){
String p[]=bufferedReader.readLine().split(" ");
w=Integer.parseInt(p[0]);//列
h=Integer.parseInt(p[1]);//行
if(w==0 && h==0) break;
for(int i=0;i<h;i++){
String s=bufferedReader.readLine();
for(int j=0;j<w;j++){
char o=s.charAt(j);
if(o=='@'){
stx=i;
sty=j;
}
g[i][j]=o;
}
}
res=1;
st=new boolean[N][N];
dfs(stx,sty);
System.out.println(res);
}
}
}