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;
}
}
}
언제쯤... 흑
[코드트리] 기울어진 직사각형 (0) | 2025.01.24 |
---|---|
[BJ] 1167 : 트리의 지름 (0) | 2025.01.24 |
[프로그래머스] 경주로 건설 (0) | 2025.01.22 |
[BJ] 2056 : 작업 - unsolved (0) | 2025.01.19 |
[BJ] 1976 : 여행가자 - unsolved (0) | 2025.01.19 |