red and black 杭电1312 java深搜

```
//将'.'看做是通路 将'#'看做是墙, 按顺时针方向,利用深度优先搜索递归```

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] ;
                }
        }
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值