/
BAEKJOON 14500
70 lines (64 loc) · 1.96 KB
/
BAEKJOON 14500
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static int ans, N, M;
static int[][] map;
static boolean[][] visit;
static int dy[] = { -1, 1, 0, 0 }, dx[] = { 0, 0, -1, 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());
map = new int[N][M];
visit = new boolean[N][M];
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());
}
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
visit[i][j] = true;
dfs(i, j, 0, 0);
visit[i][j] = false;
getSpecialSum(i, j);
}
}
System.out.println(ans);
}
public static void dfs(int y, int x, int length, int sum) {
if (length == 4) {
ans = Math.max(ans, sum);
return;
}
for (int i = 0; i < 4; i++) {
int ny = y + dy[i];
int nx = x + dx[i];
if (nx < 0 || ny < 0 || nx >= M || ny >= N||visit[ny][nx]) continue;
visit[ny][nx] = true;
dfs(ny, nx, length + 1, sum + map[ny][nx]);
visit[ny][nx] = false;
}
}
public static void getSpecialSum(int y, int x) {
if (x - 1 >= 0 && y - 1 >= 0 && x + 1 < M) {
int first = map[y][x] + map[y][x - 1] + map[y][x + 1] + map[y - 1][x];
ans = Math.max(ans, first);
}
if (x - 1 >= 0 && y + 1 < N && x + 1 < M) {
int second = map[y][x] + map[y][x - 1] + map[y][x + 1] + map[y + 1][x];
ans = Math.max(second, ans);
}
if (x + 1 < M && y + 1 < N && y - 1 >= 0) {
int third = map[y][x + 1] + map[y - 1][x] + map[y + 1][x] + map[y][x];
ans = Math.max(third, ans);
}
if (x - 1 >= 0 && y - 1 >= 0 && y + 1 < N) {
int forth = map[y][x - 1] + map[y - 1][x] + map[y + 1][x] + map[y][x];
ans = Math.max(forth, ans);
}
}
}