본문 바로가기
코딩테스트

프로그래머스 카카오 프렌즈 컬러링북

by 희안 2021. 4. 21.

레벨 2 문제였다. DFS이든 BFS이든 visit 배열을 사용해서 각 색이 가장 많이 사용된 칸의 숫자와 색의 갯수를 구하면 되는 문제였다. 금새 풀었는데 왜 때문인지 자꾸 문제 제출을 하면 틀렸다고 뜨는것..!

 

근데 전역변수 초기화를 solution안에서 해주니 성공했다. (질문에서 사람들이 다들 전역변수 초기화 solution안에서 해주면 된다고 하길래 나도 해봤다.)

뭐가 문제인지는 모르겠지만..? 아무튼 성공이다.

BFS로 푸는 것도 다시 복기해서 해봐야겠다. BFS로만 되는 문제들도 있어서 BFS로도 금새 떠올려야하는데 DFS가 익숙해서 자꾸 DFS로만 보게 된다. 

#include <vector>

using namespace std;

int visit[102][102];
int dx[4];
int dy[4];
int color; int count_ ;

void dfs(int x, int y, int col, int m, int n, vector<vector<int>> picture) {
	color++;
	visit[x][y] = 1;

	for (int i = 0; i < 4; i++) {
		int nx = x + dx[i];
		int ny = y + dy[i];
		if (nx >= 0 && ny >= 0 && nx < m && ny < n) {
			if (visit[nx][ny] == 0 && picture[nx][ny] == col) {
				dfs(nx, ny, col, m, n, picture);
			}
		}
	}

	return;
}

// 전역 변수를 정의할 경우 함수 내에 초기화 코드를 꼭 작성해주세요.
vector<int> solution(int m, int n, vector<vector<int>> picture) {
    int number_of_area = 0;
    int max_size_of_one_area = 0;
    color = 0; count_ = 0;
    dx[0] = 0; dx[1] = 0; dx[2] = 1; dx[3] = -1;
	dy[2] = 0; dy[3] = 0; dy[0] = 1; dy[1] = -1;
    for (int i = 0; i < m; i++) {
		for (int j = 0; j < n; j++) {
			visit[i][j]=0;
		}
	}
    
    vector<int> answer(2);
    answer[0] = number_of_area;
    answer[1] = max_size_of_one_area;
    
    for (int i = 0; i < m; i++) {
		for (int j = 0; j < n; j++) {
			color = 0;
			if (visit[i][j] == 0 && picture[i][j] != 0 ) {
				count_++;
				dfs(i, j, picture[i][j], m,n, picture);
			}
			answer[1] = max(answer[1], color);
		}
	}
	answer[0] = count_;
	
	//cout << answer[0] << " " << answer[1];
    return answer;
}

 

댓글