상세 컨텐츠

본문 제목

[코드트리] 테트로미노

💯ProblemSolving/문제 풀이-Java

by :부셔져버린개발자 2025. 1. 23. 12:31

본문

3개의 칸 ㄴ ㅡ 모양 이라서 dfs로 풀 수 있다는 생각을 바로 했는데 

재방문 할 수 있는 경우를 제한해야 한다는 것을 잊고 

맞왜틀한 문제

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {
	static int N, M;
	static int[][] box;
	static int LEN = 3;
	static int ans = Integer.MIN_VALUE;
	static int[][] way = { { -1, 0 }, { 1, 0 }, { 0, 1 }, { 0, -1 } };

	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
		N = Integer.parseInt(st.nextToken());
		M = Integer.parseInt(st.nextToken());
		box = new int[N][M];

		for (int n = 0; n < N; n++) {
			st = new StringTokenizer(br.readLine());
			for (int m = 0; m < M; m++) {
				box[n][m] = Integer.parseInt(st.nextToken());
			}
		}
        boolean[][] visited = new boolean[N][M];

		for (int i = 0; i < N; i++) {
			for (int j = 0; j < M; j++) {
                visited[i][j] = true;
				dfs(i, j, 0, box[i][j], visited);
                visited[i][j] = false;

			}
		}
		System.out.println(ans);
	}
    
	static void dfs(int x, int y, int cnt, int score, boolean[][] visited) {
		if (cnt == LEN-1) {
			ans = Math.max(ans, score);
			return;
		}
		for (int w = 0; w < 4; w++) {
			int nx = x + way[w][0];
			int ny = y + way[w][1];
			if (nx < 0 || nx >= N || ny < 0 || ny >= M)
				continue;
            if(visited[nx][ny])continue;
            visited[nx][ny] = true;
			dfs(nx, ny, cnt + 1, score + box[nx][ny], visited);
            visited[nx][ny] = false;
		}
	}
}

언제쯤...  흑

 

728x90

관련글 더보기