[Programmers] 가장 큰 정사각형 찾기 - 연습문제 (Dynamic Programming)

동민·2021년 3월 11일
0
// 가장 큰 정사각형 찾기 - 연습문제 (Dynamic Programming)
public class FindMaxSquare {
	public int solution(int[][] board) {
		int max = 0, cnt = 0;
		if (board.length <= 2 && board[0].length <= 2) { // 2 x 2 이하의 사각형일 때, 예외처리
			for (int[] b : board) {
				for (int ele : b) {
					if (ele == 1) {
						cnt++;
					}
				}
			}
			return cnt == 4 ? 4 : 1; // [1,1],[1,1] 일 때, 4를 리턴; [1,1],[1,0] 처럼 하나라도 0이 나오면 1을 리턴
		}
		for (int i = 1; i < board.length; i++) {
			for (int j = 1; j < board[0].length; j++) {
				if (board[i][j] == 1) {
					board[i][j] = Math.min(board[i - 1][j], Math.min(board[i][j - 1], board[i - 1][j - 1])) + 1;
					max = max < board[i][j] ? board[i][j] : max;
				}
			}
		}
		return max * max;
	}
}
profile
BE Developer

0개의 댓글

관련 채용 정보