L - Oil Deposits HDU - 1241 JAVA

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Main
{
	public static int dfs[][];
	public static char arr[][];
	public static int a, b;
	public static int all = 0;
	public static int move[][] =
	{
			{ 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())
		{
			a = sc.nextInt();
			b = sc.nextInt();
			if (a == 0 && b == 0)
			{
				return;
			}
			all=0;
			arr = new char[a][b];
			dfs = new int[a][b];
			for (int i = 0; i < a; i++)
			{
				arr[i] = sc.next().toCharArray();
			}

			// me

			for (int i = 0; i < a; i++)
			{
				for (int j = 0; j < b; j++)
				{
					if (dfs[i][j] == 0 && arr[i][j] == '@')
					{
					
						all++;
						dfs[i][j] = 1;
						dfs(i, j);
					}
				}
			}
			System.out.println(all);

		}
	}

	public static void dfs(int x, int y)
	{

		for (int i = 0; i < move.length; i++)
		{
			int xx = x + move[i][0];
			int yy = y + move[i][1];
			if (xx >= 0 && xx < a && yy >= 0 && yy < b && arr[xx][yy] == '@' && dfs[xx][yy] == 0)
			{
				dfs[xx][yy] = 1;
				dfs(xx, yy);
			}

		}

	}

}

你可能感兴趣的:(dfs,bfs)