您的位置:首页 > 编程语言 > Java开发

red and black 杭电1312 java深搜

2016-03-12 23:06 411 查看
```
//将'.'看做是通路 将'#'看做是墙, 按顺时针方向,利用深度优先搜索递归```

import java.util.*;
public class Main {
private static int count = 0;
private static int [] dx = {0,1,0,-1} ; //顺时针移动
private static int [] dy = {1,0,-1,0} ;
private static int w ;
private static int h  ;
private static char[][] array = new char[21][21] ;
public static void main(String [] args){
Scanner input = new Scanner(System.in);
while(input.hasNext()){
h = input.nextInt() ;  // 读入列数
w = input.nextInt() ;  //读入行数
String  s = input.nextLine() ; // 读取第一行剩下的空格
if(h == 0 || w == 0){
break ;
}
else{
int x = 0, y =0 ;
for(int i  = 0 ; i < w ; i++){
s = input.nextLine() ;
int index ;
if((index = s.indexOf("@")) >= 0){
x = i ;
y   = index ;
}
array[i] = s.toCharArray() ;
}
dfs(array,x,y) ;
System.out.println(count);
count = 0 ;
}
}
}
public static void dfs(char [][] array , int x , int y){
if(x >= w  || y >= h || x < 0 || y < 0){//越界,回溯
return ;
}else if(array[x][y] == '#' ){    // 遇到墙 ,回溯
return ;
}else if(array[x][y] == '.'|| array[x][y] =='@'){
count++;
array[x][y]='#' ;
for(int i = 0 ; i < 4 ; i++){
x += dx[i] ;
y += dy[i] ;
dfs(array,x,y);
x -= dx[i] ;
y -= dy[i] ;
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: