[c++] BOJ 1915 :: ๊ฐ€์žฅ ํฐ ์ •์‚ฌ๊ฐํ˜•

๋‚œ์ด๋„ : ๊ณจ๋“œ 5

๊ฑธ๋ฆฐ ์‹œ๊ฐ„ : 1์‹œ๊ฐ„ 20๋ถ„

 

๋ฌธ์ œ

๊ฐ€์žฅ ํฐ ์ •์‚ฌ๊ฐํ˜• ๋ฌธ์ œ ๋ฐ”๋กœ๊ฐ€๊ธฐ

n×m์˜ 0, 1๋กœ ๋œ ๋ฐฐ์—ด์ด ์žˆ๋‹ค. ์ด ๋ฐฐ์—ด์—์„œ 1๋กœ ๋œ ๊ฐ€์žฅ ํฐ ์ •์‚ฌ๊ฐํ˜•์˜ ํฌ๊ธฐ๋ฅผ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.

0 1 0 0
0 1 1 1
1 1 1 0
0 0 1 0

์œ„์™€ ๊ฐ™์€ ์˜ˆ์ œ์—์„œ๋Š” ๊ฐ€์šด๋ฐ์˜ 2×2 ๋ฐฐ์—ด์ด ๊ฐ€์žฅ ํฐ ์ •์‚ฌ๊ฐํ˜•์ด๋‹ค.

 

ํ’€์ด

  • ์ž‘์€ ๋ฌธ์ œ : ํ˜„์žฌ ์œ„์น˜์—์„œ ์˜ค๋ฅธ์ชฝ๊ณผ ์•„๋ž˜ ๋ฐฉํ–ฅ์œผ๋กœ ๊ฐ€์งˆ ์ˆ˜ ์žˆ๋Š” ์ •์‚ฌ๊ฐํ˜•์˜ ์ตœ๋Œ€ ํฌ๊ธฐ
  • ์žฌ๊ท€์‹
    • ํ•ด๋‹น ์œ„์น˜์—์„œ ๋‚˜ํƒ€๋‚  ์ˆ˜ ์žˆ๋Š” ์ตœ๋Œ€ ํฌ๊ธฐ ์ •์‚ฌ๊ฐํ˜•์˜ ํ•œ ๋ณ€์„ Area(row, col)์ด๋ผ๊ณ  ํ•œ๋‹ค๋ฉด
    • Area(row, col) = min(Area(row+1,col)+1, Area(row,col+1)+1, Area(row+1,col+1)+1)
  • ์กฐ๊ฑด
    • ๋ฒฝ์— ๋ถ™์–ด์žˆ์œผ๋ฉด Area๊ฐ€ 1
    • ๊ฐ’์ด 0์ด๋ฉด Area๊ฐ€ 0

 

์ฝ”๋“œ

#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>

using namespace std;

int n, m;
int arr[1001][1001];
int memo[1001][1001]; // ์ •์‚ฌ๊ฐ๊ธธ์ด ์ €์žฅ
int maxNum = 0;

int area(int row, int col) {
    if (memo[row][col] != -1) // ๋ฉ”๋ชจ์ด์ œ์ด์…˜
        return memo[row][col];

    if (arr[row][col] == 0) { // ๊ฐ’์ด 0์ด๋ฉด 0
        memo[row][col] = 0;
        return memo[row][col];
    }

    if (row == n - 1 && col == m - 1) { // ๋ฒฝ์— ๋ถ™์–ด์žˆ์œผ๋ฉด 1
        memo[row][col] = 1;
        return memo[row][col];
    }

    int nextRow, nextCol, nextDiag;
    nextRow = area(row, col + 1) + 1;
    nextCol = area(row + 1, col) + 1;
    nextDiag = area(row + 1, col + 1) + 1;

    memo[row][col] = min(min(nextRow, nextCol), nextDiag);

    return memo[row][col];
}

int main() {
    // ์ž…๋ ฅ
    cin >> n >> m;
    for (int i = 0; i < n; i++) {
        string str;
        cin >> str;
        for (int j = 0; j < m; j++) {
            arr[i][j] = str[j] - '0';
        }
    }
    // ์ดˆ๊ธฐํ™”
    memset(memo, -1, sizeof(memo));
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            int res = area(i, j);
            if (res > maxNum)
                maxNum = res;
        }
    }
    cout << maxNum * maxNum;
}

<arr ๋ฐฐ์—ด>

<memo ๋ฐฐ์—ด>

memo ๋ฐฐ์—ด ์ค‘ ๊ฐ€์žฅ ํฐ ๊ฐ’์˜ ์ œ๊ณฑ์„ ์ถœ๋ ฅ

 

๊ฒฐ๊ณผ

 

๋‹ค๋ฅธ ์‚ฌ๋žŒ์˜ ํ’€์ด

๋ฒฝ์— ๋ถ™์–ด์žˆ๋Š” ๊ฐ’์€ ๋ฏธ๋ฆฌ memo ๋ฐฐ์—ด์— ๋„ฃ์–ด๋‘๊ณ , ์žฌ๊ท€์‹์„ ์ด์šฉํ•˜์—ฌ ๋ฐ˜๋ณต๋ฌธ์œผ๋กœ ๊ตฌ์„ฑํ•˜๋ฉด ์‹œ๊ฐ„์„ ๋” ์ค„์ผ ์ˆ˜ ์žˆ๋‹ค.

https://howtolivelikehuman.tistory.com/209

https://bba-dda.tistory.com/entry/%EB%B0%B1%EC%A4%80C-1915-%EA%B0%80%EC%9E%A5-%ED%81%B0-%EC%A0%95%EC%82%AC%EA%B0%81%ED%98%95

๋ฐ˜์‘ํ˜•