특점 지점에서 시작해서 연결되어있는 Blob의 크기가 얼마인지 구하는 메서드 이다.
문제를 작게 쪼개어서 보는것이 중요하다.
public class CountCells {
public static void main(String[] args) {
System.out.println(countCells(1, 1));
}
// 결과값은 17
private static int N = 8;
private static int[][] grid = {
{0, 0, 0, 0, 0, 0, 0, 1},
{0, 1, 1, 0, 1, 1, 0, 1},
{0, 0, 0, 1, 0, 0, 0, 1},
{0, 1, 0, 0, 1, 1, 0, 0},
{0, 1, 1, 1, 0, 0, 1, 1},
{0, 1, 0, 0, 0, 1, 0, 1},
{0, 0, 0, 1, 0, 0, 0, 1},
{0, 1, 1, 1, 0, 1, 0, 0},
};
private static int BACKGRUND_COLOR = 0;
private static int IMAGE_COLOR = 1; // 색 칠해져있으면 1
private static int ALREADY_COUNTED = 2; // 이미 카운트 되었으면 2
public static int countCells(int x, int y) {
int result;
if (x < 0 || y < 0 || x >= N || y >= N) return 0;
else if (grid[x][y] != IMAGE_COLOR) return 0; // 색상 없으면 count안하고 0 리턴
else {
grid[x][y] = ALREADY_COUNTED;
return 1 + countCells(x - 1, y + 1) + countCells(x, y + 1)
+ countCells(x + 1, y + 1) + countCells(x - 1, y)
+ countCells(x + 1, y) + countCells(x - 1, y - 1)
+ countCells(x, y - 1) + countCells(x + 1, y - 1);
// 상하좌우, 각 대각선에서도 연결된곳 있는지 계산해서 더해주기
}
}
}
'미니 프로젝트' 카테고리의 다른 글
알고리즘 - 미로 출구찾기(재귀) (0) | 2023.03.22 |
---|---|
TRPG게임 만들기 - 배열, 형변환(String -> int) (0) | 2023.03.12 |
글자 대체 프로그램 - 배열, for 반복문 (0) | 2023.03.11 |
계산기 만들기 - switch, do-while, ArrayList (0) | 2023.03.11 |