원본 문제 : 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;
}
}
'프로그래머스 > 카카오 코딩테스트' 카테고리의 다른 글
[프로그래머스] (틀림)후보키 (42890)(java) (0) | 2019.05.30 |
---|---|
[프로그래머스] 카카오 오픈채팅방 (42888)(java) (0) | 2019.05.30 |
[프로그래머스] 카카오 프렌즈 컬러링북 (java)(1829) (0) | 2019.05.28 |
[프로그래머스] 카카오 프렌즈 컬러링북(1829)(java) (0) | 2019.04.26 |
댓글