본문 바로가기

카테고리 없음

Counting Cells In a Blob - 재귀함수(recursion) 사용, 자바

코드

 

public class CCIB {

    public static int CountingCellInaBlob(int[][] grid, int x, int y){
        int cont = 0;
        if (x>= 0 && y>=0 && x<grid.length && y < grid[0].length) {
            if (grid[x][y] == 0)
                return 0;
            else if (grid[x][y] == 1){
                grid[x][y] = 2;
                cont++;
                cont = cont + CountingCellInaBlob(grid, x, y - 1);
                cont = cont + CountingCellInaBlob(grid, x + 1, y - 1);
                cont = cont + CountingCellInaBlob(grid, x + 1, y);
                cont = cont + CountingCellInaBlob(grid, x + 1, y + 1);
                cont = cont + CountingCellInaBlob(grid, x, y + 1);
                cont = cont + CountingCellInaBlob(grid, x - 1, y + 1);
                cont = cont + CountingCellInaBlob(grid, x - 1, y);
                cont = cont + CountingCellInaBlob(grid, x - 1, y - 1);
                return cont;
            }
        }
        return 0;
    }

    public static void main(String[] args){
        int[][] grid = {
                {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}
        };
        int x =7;
        int y =7;
        System.out.println("Blob size : "+CountingCellInaBlob(grid,x,y));
    }
}