본문 바로가기

코딩 테스트/백준

[백준 1051번 문제, JAVA] 숫자 정사각형

728x90
반응형

문제

N×M크기의 직사각형이 있다. 각 칸에는 한 자리 숫자가 적혀 있다. 이 직사각형에서 꼭짓점에 쓰여 있는 수가 모두 같은 가장 큰 정사각형을 찾는 프로그램을 작성하시오. 이때, 정사각형은 행 또는 열에 평행해야 한다.


코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import static java.lang.System.exit;

public class Main {
    public static void main(String[] args) throws IOException {
        final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] lines = br.readLine().split("\\s+");
        int index = Integer.parseInt(lines[0]);
        int length = Integer.parseInt(lines[1]);
        int[][] squares = new int[index][length];
        for (int i = 0; i < index; i++) {
            int[] x = Arrays.stream(br.readLine().split(""))
                    .mapToInt(Integer::parseInt)
                    .toArray();
            squares[i] = x;
        }

        int currentLength = Math.min(index, length);
        while(currentLength > 1) {
            for (int i = 0; i <= index - currentLength; i++) {
                for (int j = 0; j <= length - currentLength; j++) {
                    int value = squares[i][j];
                    if (value == squares[i][j + currentLength - 1]
                            && value == squares[i + currentLength - 1][j]
                            && value == squares[i + currentLength - 1][j + currentLength - 1]) {
                        System.out.println(currentLength * currentLength);
                        return;
                    }
                }
            }
            currentLength--;
        }
        System.out.println(currentLength * currentLength);
    }
}

해결

생각


참고

링크

 

 

 

728x90
반응형