-
백준 / 14500 / 테트로미노Algorithm 2020. 5. 3. 11:08
문제
입력
첫째 줄에 종이의 세로 크기 N과 가로 크기 M이 주어진다. (4 ≤ N, M ≤ 500)
둘째 줄부터 N개의 줄에 종이에 쓰여 있는 수가 주어진다. i번째 줄의 j번째 수는 위에서부터 i번째 칸, 왼쪽에서부터 j번째 칸에 쓰여 있는 수이다. 입력으로 주어지는 수는 1,000을 넘지 않는 자연수이다.
출력
첫째 줄에 테트로미노가 놓인 칸에 쓰인 수들의 합의 최댓값을 출력한다.
입출력 예
해결
'ㅜ'를 제외한 블록들은 dfs로 한 번에 탐색할 수 있다.
오른쪽을 탐색한다고 예를 들었을 때, 4가지 경우의 수로 'ㅜ'를 제외한 블록들을 표현한다. 즉, 깊이 4만큼만 탐색하면 자연스럽게 전부 해당이 된다는 것을 의미한다. 함수명은 dfs()로 하겠다.
'ㅜ'는 십자가 모양에서 하나를 빼면 된다. 이 4가지 경우 중에서 가장 큰 값을 찾으면 된다. 이런 패턴을 찾는 함수를 exception() 이라고 하겠다.
dfs 방식으로 진행하나 경우의 수를 분리해서 독립적으로 구현이 가능한지를 물어보는 문제이다.
코드
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersimport java.util.*; public class tetris { public static int n, m, max = 0; public static int[][] arr; public static boolean[][] check; public static int[] dx = {0, 0, 1, -1}; public static int[] dy = {1, -1, 0, 0}; public static void dfs(int x, int y, int depth, int sum) { if(depth == 4) { max = Math.max(max, sum); return; } for(int i = 0 ; i < 4 ; i++) { int ax = x + dx[i]; int ay = y + dy[i]; if(ax >= 0 && ay >= 0 && ax < n && ay < m && check[ax][ay] == false) { check[ax][ay] = true; dfs(ax, ay, depth + 1, sum + arr[ax][ay]); check[ax][ay] = false; } } } public static void exception(int x, int y) { // 상하좌우 이동 for(int i = 0 ; i < 4 ; i++) { int total = arr[x][y]; boolean flag = true; // 십자가에서 하나 뺀거니까 3번만 이동 for(int j = 0 ; j < 3 ; j++) { int ax = x + dx[(i + j) % 4]; int ay = y + dy[(i + j) % 4]; if(ax >= 0 && ay >= 0 && ax < n && ay < m) { total += arr[ax][ay]; } else { flag = false; break; } } if(flag) max = Math.max(max, total); } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); n = sc.nextInt(); m = sc.nextInt(); arr = new int[n][m]; check = new boolean[n][m]; for(int i = 0 ; i < n ; i++) for(int j = 0 ; j < m ; j++) arr[i][j] = sc.nextInt(); for(int i = 0 ; i < n ; i++) for(int j = 0 ; j < m ; j++) { check[i][j] = true; dfs(i, j, 1, arr[i][j]); exception(i, j); check[i][j] = false; } System.out.println(max); return; } } 느낀점
처음 테트리스 모양을 보고 대칭, 이동, 회전을 해야한다는 생각에 막막했었는데 솔루션을 보니 무릎을 쳤다. 왜 저런 생각을 못했을까..? 아무 도움 없이 이런 문제의 해답을 찾으려면 얼마나 더 해야할까..ㅠㅠ 더 열심히 해야겠다.
출처
https://www.acmicpc.net/problem/14500
14500번: 테트로미노
폴리오미노란 크기가 1×1인 정사각형을 여러 개 이어서 붙인 도형이며, 다음과 같은 조건을 만족해야 한다. 정사각형은 서로 겹치면 안 된다. 도형은 모두 연결되어 있어야 한다. 정사각형의 변�
www.acmicpc.net
https://hyeooona825.tistory.com/60
[백준 14500] 테트로미노
이 문제는 4개짜리 테트로미노 블럭을 주어진 이차원 배열에 놨을 때 배열의 값의 합이 최대가 되는 값을 구하는 문제입니다. 폴리오미노의 조건은 아래와 같습니다. 정사각형은 서로 겹치면 안된다. 도형은 모두..
hyeooona825.tistory.com
'Algorithm' 카테고리의 다른 글
SWEA / 1208 / flatten (0) 2020.04.29 SWEA / 1244 / 최대 상금 (1) 2020.04.29 SWAE / 1204 / 최빈수 구하기 (0) 2020.04.28 SWEA / 1206 / View (0) 2020.04.28 백준 / 5585 / 거스름돈 (0) 2020.03.24