[구현] 백준 1051 숫자 정사각형

Halo·2025년 5월 26일
0

Algorithm

목록 보기
51/85
post-thumbnail

🔍 Problem

1051 숫자 정사각형


📃 Input&Output


🌁 문제 배경

가. 접근 방법
윈도우를 만들어서 각 꼭지점을 조사하고 최대 넓이를 갱신하는 방향으로 구현한다.

나. 사용할 알고리즘 선택
구현


📒 해결 과정

가. 윈도우 크기별 1,1 좌표를 구한다.
나. 해당 윈도우의 1,1을 파라미터로 하는 정사각형 꼭지점이 모두 같은지 확인하는 함수를 만들어 매트릭스의 모든 좌표를 순회한다.

다. 위의 순회에서 계속해서 최대값을 갱신한다.


💻 Code

import java.util.*;
import java.io.*;
import java.lang.*;

public class P1051 {

    static int N, M;
    static int[][] mat;

    public static boolean IsSquareWithEqualCorners(int x, int y, int offset) {
        int[] dx = {0, 0, offset, offset};
        int[] dy = {0, offset, 0, offset};
        int val = mat[x][y];
        for (int i = 0; i < 4; i++) {
            if (x + dx[i] < N && y + dy[i] < M) {
                if (mat[x + dx[i]][y + dy[i]] == val) {

                } else {
                    return false;
                }

            } else {
                return false;
            }
        }
        return true;
    }

    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);

        int max = 1;
        N = sc.nextInt();
        M = sc.nextInt();
        sc.nextLine();
        mat = new int[N][M];

        for (int i = 0; i < N; i++) {
            String line = sc.nextLine();
            for (int j = 0; j < M; j++) {
                mat[i][j] = line.charAt(j) - '0';
            }
        }

        for (int offset = 1; offset <= Math.min(N, M); offset++) {
            for (int i = 0; i < N; i++) {
                for (int j = 0; j < M; j++) {
                    if (IsSquareWithEqualCorners(i, j, offset)) {
                        max = Math.max(max, (int) Math.pow(offset + 1, 2));
                    }
                }
            }
        }

        System.out.println(max);
    }
}

🤔 느낀점

단순구현이 부족하다는 점을 코테 후에 많이 느껴서 풀게되었는데 잘 한거 같다. 구현문제 많이 풀어야지.

profile
새끼 고양이 키우고 싶다

0개의 댓글