변명은 만개 결과는 한개

[백준 1051] 숫자 정사각형 (java) 본문

공부/Problem Solving

[백준 1051] 숫자 정사각형 (java)

노마십가 2022. 5. 3. 01:49
728x90
반응형

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

 

1051번: 숫자 정사각형

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

www.acmicpc.net

import java.io.*;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Stream;

public class Main {
    static int maxSize = 0;
    static int width = 0;
    static int height = 0;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//        StringTokenizer st = new StringTokenizer(br.readLine(), " ");

        // input Matrix
        String[] str = br.readLine().split(" ");
        height = Integer.parseInt(str[0]);
        width = Integer.parseInt(str[1]);

        String[][] matrix = new String[height][width];

        for (int i = 0; i < height; i++) {
            String[] strs = br.readLine().split("");
            for (int j = 0; j < width; j++) {
                matrix[i][j] = strs[j];
            }
        }

        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                for (int size = 0; size + j < width; size++) {
//                    System.out.println("size,j:" + size + "," + j);
                    squareCheck(matrix, j, i, size);
                }
            }
        }

        System.out.println(maxSize);
    }

    static void squareCheck(String[][] inputMatrix, int x, int y, int size) {
        if (x + size >= width || y + size >= height) return;

        if (inputMatrix[y][x + size].equals(inputMatrix[y][x])) {
            if (inputMatrix[y + size][x].equals(inputMatrix[y][x])) {
                if (inputMatrix[y + size][x + size].equals(inputMatrix[y][x])) {
                    size++;
                    if (maxSize < size*size) {
                        maxSize = size*size;
                    }
                }
            }
        }
    }
}

 

 

굳이 함수로 빼야했나 싶긴한데 나눠놓으니까 구현할때 편함.. :/

728x90
반응형