본문 바로가기

플밍 is 뭔들/알고리즘

Recursion의 응용 [Counting Cells in a Blob]

※ 문제 설명



      private static int BACKGROUND_PIXEL = 0;
       private static int IMAGE_PIXEL = 1;
       private static int VISITED_IMAGE_PIXCEL = 2;
       
       private static 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}
       };
       
       public static void main(String[] args) {
              
              int x=0;
              int y=0;
              int blob =0;
              ArrayList<Integer> countList = new ArrayList<>();
              
              while( x != 7 || y != 7 ){
                     if(grid[x][y]==IMAGE_PIXEL){
                           countList.add(countCellinBlob(x, y));
                           blob ++;
                     }else{
                           if(y<7){
                                  y++;
                           }else{
                                  y=0;
                                  x++;
                           }
                     }
              }
              
              System.out.println("Blob의 수 : " + blob);
              System.out.println("각각의  Blob의 Size는 ");
              for(int i =0; i < countList.size(); i++){
                     System.out.print(countList.get(i));
                     if(i<countList.size()-1){
                           System.out.print(", ");
                     }
              }
              
       }
   
       public static int countCellinBlob(int x, int y){
              
              if(x<0 || x>7 || y<0 || y>7){
                     return 0;
              }
              else if(grid[x][y] == BACKGROUND_PIXEL || grid[x][y] == VISITED_IMAGE_PIXCEL){
                     return 0;
              }else{
                     grid[x][y] = VISITED_IMAGE_PIXCEL;
                     
                     return countCellinBlob(x,y+1) + countCellinBlob(x+1,y+1) + countCellinBlob(x+1,y)
                           + countCellinBlob(x+1,y-1) + countCellinBlob(x,y-1) + countCellinBlob(x-1,y-1)
                           + countCellinBlob(x-1,y) + countCellinBlob(x-1,y+1) + 1;
              }
       }