red and black 杭电1312 java深搜

来源:互联网 发布:扫码软件 编辑:程序博客网 时间:2024/05/21 11:33
```//将'.'看做是通路 将'#'看做是墙, 按顺时针方向,利用深度优先搜索递归```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] ;                }        }    }}
0 0