완전탐색에 좀 약한것같아서 완전탐색에 온 힘을 다하고있는데 그래도 문제가 풀리니까 재밌네 ㅋㅋ
재귀에 대한 감도 좀 잡은 것 같다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static int[][] map;
static boolean[][] visited;
static int answer = 0;
static int N, M;
public static void init() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
map = new int[N + 3][M + 3];
visited = new boolean[N + 3][M + 3];
for(int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
for(int j = 0; j < M; j++) {
map[i][j] = Integer.parseInt(st.nextToken());
}
}
}
public static void dfs(int x, int y, int depth, int sum) {
if(depth == 4)
{
answer = Math.max(answer, sum);
return ;
}
visited[x][y] = true;
if(y < M && !visited[x][y + 1]) //오른쪽
{
dfs(x, y + 1, depth + 1, sum + map[x][y + 1]);
}
if(x < N && !visited[x + 1][y]) { //아래
dfs(x + 1, y, depth + 1, sum + map[x + 1][y]);
}
if(x > 0 && !visited[x - 1][y]) { //왼쪽
dfs(x - 1, y, depth + 1, sum + map[x - 1][y]);
}
if(y > 0 && !visited[x][y - 1]) { //위쪽..? 이건 굳이 해야하나?
dfs(x, y - 1, depth + 1, sum + map[x][y - 1]);
}
visited[x][y] = false;
}
public static int getMax(int a, int b, int c) {
return a > b ? a > c ? a : c : b > c ? b : c ;
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
init();
for(int i = 0; i < N; i++) {
for(int j = 0; j < M; j++) {
dfs(i, j, 0, 0);
}
}
int w, h, temp1 = 0, temp2 = 0, temp3 = 0, temp4 = 0;
for(int i = 0; i < N; i++) {
for(int j = 0; j < M; j++) {
w = map[i][j] + map[i][j + 1] + map[i][j + 2];
h = map[i][j] + map[i + 1][j] + map[i + 2][j];
temp1 = w + map[i + 1][j + 1]; // ㅜ
temp2 = h + map[i + 1][j + 1]; // ㅏ
answer = getMax(answer, temp1, temp2);
if(i > 0) {
temp3 = w + map[i - 1][j + 1]; //ㅗ
}
if(j > 0) {
temp4 = h + map[i + 1][j - 1]; //ㅓ
}
answer = getMax(answer, temp3, temp4);
}
}
System.out.print(answer);
}
}