본문 바로가기
프로그래머스/카카오 코딩테스트

[프로그래머스] 카카오 프렌즈 컬리링북 (1829)(java)

by 유줘니 2019. 5. 29.

원본 문제 : https://programmers.co.kr/learn/courses/30/lessons/1829?language=java

풀이 참고 : https://lkhlkh23.tistory.com/48

 

 

 

 

import java.util.Stack;

class Solution {
    public static boolean[][] visited;
	public static int[][] image;
	public static Stack<Integer> stackX;
	public static Stack<Integer> stackY;
    
    public int[] solution(int m, int n, int[][] picture) {
      int[] answer = new int[2];
	    
	    visited = new boolean[m][n];
	    image = picture.clone();
	    stackX = new Stack<>();
	    stackY = new Stack<>();
	    
	    for(int i = 0 ; i < m ; i++) {
	    	for(int j = 0 ; j < n ; j++) {
	    		int count = 0;
	    		if(image[i][j] > 0 && visited[i][j] == false) {
	    			count += plus(i,j);
	    			answer[0] += 1;
	    		}
	    		while(!stackX.isEmpty()) {
	    			int x = stackX.pop();
	    			int y = stackY.pop();
	    			
	    			if(y>0 && image[y][x]==image[y-1][x] && visited[y-1][x]==false)
	    				count += plus(y-1,x);
	    			if(x>0 && image[y][x]==image[y][x-1] && visited[y][x-1]==false)
	    				count += plus(y,x-1);
	    			if(y<m-1 && image[y][x]==image[y+1][x] && visited[y+1][x]==false)
	    				count += plus(y+1,x);
	    			if(x<n-1 && image[y][x]==image[y][x+1] && visited[y][x+1]==false)
	    				count += plus(y,x+1);
	    		}
	    		answer[1] = Math.max(count, answer[1]);
	    	}
	    }
	    return answer;
  }
    public static int plus(int i, int j) {
		stackY.push(i);
		stackX.push(j);
		visited[i][j]=true;
		return 1;
	}
    
}

댓글