본문 바로가기

problem solving

[프로그래머스]컬러링북

주의!! // 전역 변수를 정의할 경우 함수 내에 초기화 코드를 꼭 작성해주세요. 

코드에서 전역변수 사용하고 함수내에서 따로 초기화하지 않는다면 틀리게 된다.

 

DFS를 사용했는데  check 배열에 다른 값을 부여해서  구간을 분리할 수 있도록 했다.

DFS를 도는 동안 count를 증가시켜 한 구간의 순회가 끝난 후 max변수와 비교해 삽입할 수 있도록 했다.

#include <vector>
 
using namespace std;
 
typedef struct {
    int y, x;
} dif;
 
dif dir[4= { {10}, {-10}, {01}, {0-1} };
 
long long check[101][101= { 0 };
int count = 0;
vector<vector<int>> map;
 
void DFS(int row, int col, int y, int x, int color, long long val) {
    check[y][x] = color;
    count++;
    
    for(int i = 0; i < 4; i++) {
        int tempY = y + dir[i].y;
        int tempX = x + dir[i].x;
        if(tempX < 0 || tempX >= col || tempY < 0 || tempY >= row) { continue; }
        if(check[tempY][tempX] == color || map[tempY][tempX] != val) { continue; }
        DFS(row, col, tempY, tempX, color, val);
    }
}
 
// 전역 변수를 정의할 경우 함수 내에 초기화 코드를 꼭 작성해주세요.
vector<int> solution(int m, int n, vector<vector<int>> picture) {
    int number_of_area = 0;
    int max_size_of_one_area = 0;
     
    for(int i = 0; i < 101; i++) {
        for(int j = 0; j < 101; j++) {
            check[i][j] = 0;
        }
    }
    
    map.resize((int)picture.size());
    copy(picture.begin(), picture.end(), map.begin());   
    // map = picture; 
    long long max = 0;
    int color = 1;
    for(int i = 0; i < m; i++) {
        for(int j = 0; j < n; j++) {
            if(!check[i][j] && picture[i][j]) {
                DFS(m, n, i, j, color, picture[i][j]);   
                color++;
                max = max > count ? max : count;
                count = 0;
            }
        }
    }
    
    vector<int> answer(2);
    answer[0= color - 1;
    answer[1= max;
    return answer;
}
cs

'problem solving' 카테고리의 다른 글

[프로그래머스]가장 큰 수  (0) 2020.03.09
[프로그래머스]조이스틱  (0) 2020.03.08
[프로그래머스]문자열 압축  (0) 2020.03.07
[프로그래머스]프린터  (0) 2020.03.07
[프로그래머스]주식가격  (0) 2020.03.07