Apr 072012
 

 

Lake Counting (POJ No.2386)

 

재귀 함수를 이용하여 구현하였다.

import java.util.Scanner;

public class P2386 {

	public static int[][] arr = new int[102][102];

	public static void check(int x, int y, int num) {

		arr[x][y] = num;

		if (arr[x - 1][y] == 0)
			check(x - 1, y, num);

		if (arr[x + 1][y] == 0)
			check(x + 1, y, num);

		if (arr[x - 1][y - 1] == 0)
			check(x - 1, y - 1, num);

		if (arr[x][y - 1] == 0)
			check(x, y - 1, num);

		if (arr[x + 1][y - 1] == 0)
			check(x + 1, y - 1, num);

		if (arr[x - 1][y + 1] == 0)
			check(x - 1, y + 1, num);

		if (arr[x][y + 1] == 0)
			check(x, y + 1, num);

		if (arr[x + 1][y + 1] == 0)
			check(x + 1, y + 1, num);

	}

	public static void main(String[] args) {

		int x, y;
		int num = 0;
		Scanner scan = new Scanner(System.in);

		x = scan.nextInt();
		y = scan.nextInt();

		for (int i = 0; i <= x + 1; i++)
		{
			for (int j = 0; j <= y + 1; j++)
			{
				arr[i][j] = -1;
			}
		}

		for (int i = 1; i <= x; i++)
		{
			char[] tmp = scan.next().toCharArray();

			for (int j = 0; j < y; j++)
			{
				if (tmp[j] == 'W')
				{
					arr[i][j + 1] = 0;
				}
			}
		}

		for (int i = 1; i <= x; i++)
		{
			for (int j = 1; j <= y; j++)
			{
				if (arr[i][j] == 0)
				{
					check(i, j, ++num);
				}
			}
		}

		System.out.println(num);
	}
}

 


 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)

This site uses Akismet to reduce spam. Learn how your comment data is processed.