์ํ์ข์ฐ, ๋๊ฐ์ ์ผ๋ก ๋ง๋ฟ์์๋ ์
๋ค์ ํ๋์ ๋ฌถ์์ผ๋ก ๋ณด๊ณ , ๊ทธ ๋ฉ์ด๋ฆฌ๊ฐ ์ด ๋ช๊ฐ์ธ์ง ๊ตฌํ๋ ๋ฌธ์
package practice.algorithm.recursion;
/**
* counting cells in a blob
* ์ํ์ข์ฐ ๋๊ฐ์ ์ผ๋ก ์ธ์ ํ ์
์ ๋ฉ์ด๋ฆฌ๋ฅผ ์ฐพ๋ ๋ฌธ์
* 1. ์ฐ์ ๋๋ฅผ ๋ธ๋กญ์ผ๋ก ์นด์ดํธํ๊ณ ,
* 2. ๋์ ์ธ์ ํ 8๊ฐ์ ์
์ ๋ํ์ฌ ์ธ์ ํ ๋ธ๋กญ์ด ์๋์ง ์ฒดํฌํ ํ, ์๋ค๋ฉด ์นด์ดํธ๋ฅผ ์ฆ๊ฐ์ํจ๋ค.
*
* ํฝ์
ํจ์ ๋ด์์๋
* 1. ๋ฒ์ ๋ด์ธ์ง ๊ฒ์ฌ
* 2. ์ด๋ฏธ์ง ํฝ์
์ธ์ง ๊ฒ์ฌ = ๋ฐฑ๊ทธ๋ผ์ด๋ ์ปฌ๋ฌ๊ฐ ์๋๊ณ + ์ด๋ฏธ ๋ฐฉ๋ฌธํ ๊ณณ๋ ์๋ ๊ณณ
* 3. 1๋ฒ๊ณผ 2๋ฒ์ ํต๊ณผํ ์
์ ๋์ ์
์ด๋ฏ๋ก ๋ฐฉ๋ฌธ์ฒ๋ฆฌํ๊ณ ์ธ์ ํ ์
์ ๊ฐ์๋ฅผ ์ฌ๊ท ํธ์ถํ์ฌ ๋ชจ๋ ํฉํ ๊ฐ์ ๋ธ๋กญ ํฌ๊ธฐ๋ก ๊ฐ์ฃผํ์ฌ ๋ฐํํ๋ค.
* */
public class CountingCellsBlob {
private static final int BACKGROUND_COLOR = 0;
private static final int PIXEL_COLOR = 1;
private static final int ALREADY_COUNTED = 2;
private static final int[][] pixels = {
{1, 0, 0, 0, 0, 0, 0, 1},
{0, 1, 1, 0, 0, 1, 0, 0},
{1, 1, 0, 0, 1, 0, 1, 0},
{0, 0, 0, 0, 0, 1, 0, 0},
{0, 1, 0, 1, 0, 1, 0, 0},
{0, 1, 0, 1, 0, 1, 0, 0},
{1, 0, 0, 0, 1, 0, 0, 1},
{0, 1, 1, 0, 0, 1, 1, 1}
};
public static void main(String[] args) {
for (int i = 0; i < pixels.length; i++) {
for (int j = 0; j < pixels.length; j++) {
int result = countPixel(i, j);
if (result > 0) {
System.out.println(result);
}
}
}
}
private static int countPixel(int x, int y) {
if (x < 0 || y < 0 || x >= pixels.length || y >= pixels.length) {
return 0;
}
if (pixels[x][y] != PIXEL_COLOR) {
return 0;
}
pixels[x][y] = ALREADY_COUNTED;
return 1 + countPixel(x, y-1) + countPixel(x+1, y-1) + countPixel(x+1, y)
+ countPixel(x+1, y+1) + countPixel(x, y+1) + countPixel(x-1, y+1)
+ countPixel(x-1, y) + countPixel(x-1, y-1);
}
/**
* 5
* 1
* 13
* 5
* */
}