취미처럼

[백준] 14500번 테트로미노 본문

Algorithm/백준

[백준] 14500번 테트로미노

sirius 2021. 3. 2. 11:19
https://www.acmicpc.net/problem/14500
 

14500번: 테트로미노

폴리오미노란 크기가 1×1인 정사각형을 여러 개 이어서 붙인 도형이며, 다음과 같은 조건을 만족해야 한다. 정사각형은 서로 겹치면 안 된다. 도형은 모두 연결되어 있어야 한다. 정사각형의 변

www.acmicpc.net

 

import java.util.*;


public class Main {

    static int N, M;
    static int[][] map;
    static int[] dy = {-1, 1, 0, 0};
    static int[] dx = {0, 0, -1, 1};
    static boolean[][] visit;
    static int max = Integer.MIN_VALUE;

    public static void main(String[] args) throws Exception {

        Scanner sc = new Scanner(System.in);
        N = sc.nextInt();
        M = sc.nextInt();
        map = new int[N][M];
        visit = new boolean[N][M];

        for(int i = 0; i < N; i++) {
            for(int j = 0; j < M; j++) {
           		map[i][j] = sc.nextInt();
            }
        }

        for(int i = 0; i < N; i++) {
            for(int j = 0; j < M; j++) {
                visit[i][j] = true;
                dfs(i, j, map[i][j], 1);
                visit[i][j] = false;
            }
        }
        System.out.println(max);  
    }

    private static void dfs(int y, int x, int sum, int count) {
        // 테트로미노 완성 시 수들의 합 중 최대값
        if(count >= 4 ) {
        	max = Math.max(max, sum);
        	return;
        }

        // 상하좌우 탐색
        for(int i = 0; i < 4; i++) {
            // 이동
            int ny = y + dy[i];
            int nx = x + dx[i];

            // 범위 벗어나는지 체크
            if(ny < 0 || ny >= N || nx < 0 || nx >= M ) {
            	continue;
            }

            // 아직 방문하지 않은 곳 처리
            if(!visit[ny][nx]) {

                // (ㅗ) 모양 탐색을 위해 2번째 칸에서 다시 상하좌우 탐색 ( ㅗ, ㅜ, ㅓ, ㅏ)
                if(count == 2) {
                    visit[ny][nx] = true;
                    dfs(y, x, sum + map[ny][nx], count + 1);
                    visit[ny][nx] = false;
                }

                // 이동한 것으로 탐색
                visit[ny][nx] = true;
                dfs(ny, nx, sum + map[ny][nx], count + 1);
                visit[ny][nx] = false;
            }
        }    
    }



}

'Algorithm > 백준' 카테고리의 다른 글

[백준] 1748번 수 이어쓰기1  (0) 2021.03.02
[백준] 6064번 카잉 달력  (0) 2021.03.02
[백준] 1107번 리모컨  (0) 2021.03.02
[백준] 1476번 날짜 계산  (0) 2021.02.25
[백준] 3085번 사탕 게임  (0) 2021.02.25
Comments