ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [1505] 불 켜기
    BOJ 2022. 1. 26. 08:00

    https://www.acmicpc.net/problem/1505

     

    1505번: 불 켜기

    세준이는 N×M 크기의 보드를 가지고 있고, 보드는 1×1 크기의 칸으로 나누어져 있다. 각 칸에는 전구가 하나씩 있다. 전구를 한번 만지면 전구의 상태가 반전된다. 즉, 켜있는 전구를 만지면 불이

    www.acmicpc.net

    <문제>

    첫 행, 첫 열을 브루트포스하게 선택한 뒤, (1, 1)부터 (n-1, m-1)까지 순차적으로 훑으며

    (i-1, j-1)이 꺼져있을 때 (i, j)를 켠다는 그리디적 방식으로 완전탐색이 가능하다.

     

    <소스코드>

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    #include <bits/stdc++.h>
    using namespace std;
    int n, m, cnt, dy[9= {0-1-101110-1},
                   dx[9= {001110-1-1-1};
    bool a[10][10];
    bool cloneMap[10][10];
    void toggle(int y, int x) {
        cnt++;
        for (int i = 0; i < 9; i++) {
            int ny = y + dy[i];
            int nx = x + dx[i];
            if (ny >= 1 && ny <= n && nx >= 1 && nx <= m) a[ny][nx] = 1 - a[ny][nx];
        }
    }
    bool isAllOn(void) {
        for (int i = 1; i <= n; i++)
            for (int j = 1; j <= m; j++)
                if (a[i][j] == 0return false;
        return true;
    }
    int main(void) {
        cin >> n >> m;
        int i, j;
        for (i = 1; i <= n; i++)
            for (j = 1; j <= m; j++) {
                char x;
                cin >> x;
                if (x == '*') a[i][j] = 1;
                cloneMap[i][j] = a[i][j];
            }
        int bitX = (1 << m);
        int bitY = (1 << n);
        int ans = 54321;
        for (int btx = 0; btx < bitX; btx++) {
            for (int bty = 0; bty < bitY; bty++) {
                for (i = 1; i <= n; i++)
                    for (j = 1; j <= m; j++) a[i][j] = cloneMap[i][j];
                cnt = 0;
                for (i = 0; i < m; i++)
                    if (btx & (1 << i)) toggle(1, i + 1);
                for (i = 0; i < n; i++)
                    if (bty & (1 << i)) toggle(i + 11);
                for (i = 2; i <= n; i++)
                    for (j = 2; j <= m; j++)
                        if (a[i - 1][j - 1== 0) toggle(i, j);
                if (isAllOn()) ans = min(cnt, ans);
            }
        }
        if (ans == 54321) ans = -1;
        cout << ans;
        return 0;
    }
    cs

     

    'BOJ' 카테고리의 다른 글

    [10422] 괄호  (0) 2022.01.29
    [2216] 문자열과 점수  (0) 2022.01.29
    [16935] 배열 돌리기 3  (0) 2022.01.26
    [4375] 1  (0) 2022.01.26
    [17471] 게리맨더링  (0) 2022.01.25

    댓글