hdu 1241 Oil Deposits 深搜 Ac

1241 hdu原链接处
package cn.hncu.start;

import java.util.Scanner;

public class p1241 {
		static int n,m;
		final static int b[][]={//因为题目要求连起来的才算一个,所以必须要把上下左右等八个坐标表示出来
			{0,-1},
			{0,1},
			{-1,0},
			{1,0},
			{-1,-1},
			{-1,1},
			{1,-1},
			{1,1}
		};
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		while(sc.hasNext()){
			 n=sc.nextInt();
			 m=sc.nextInt();
			 if(n==0&&m==0){
				 break;
			 }
			 
			 //字符收集
			char[][] a=new char[n][m];//存字符
			for(int i=0;i<n;i++){
				String str=sc.next();//先收取一行,然后后面单个解析
				 for(int j=0;j<m;j++){
					a[i][j]=str.charAt(j);//解析
				 }
			}
			int count=0;//用来统计有多少个
			for(int i=0;i<n;i++){
				for(int j=0;j<m;j++){
					if(a[i][j]=='@')//若满足条件,开始进行深搜
					{
						dfs(a,i,j);
						count +=1;//一次深搜结束后,就能确定为一个油田
					}
				}
			}
			System.out.println(count);//输出要求
		}
	}
	private static void dfs(char[][] a,int start, int end) {
			int x=0,y=0;
			for(int i=0;i<8;i++){
				x=start+b[i][0];//该坐标点的x标和y坐标开始遍历,找出符合条件的
				y=end+b[i][1];
			
			if(x<n&&x>=0 && y>=0&&y<m && a[x][y]=='@'){//符合这个条件
				a[x][y]='*';//方便下次不去访问;其实也可以用整数来表示,不过前面就需要在加数组表示。
				dfs(a,x,y);
			}
<span style="white-space:pre">		</span>}
		}
	}
	

	

你可能感兴趣的:(深搜)