-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain2.java
More file actions
67 lines (57 loc) · 1.9 KB
/
Main2.java
File metadata and controls
67 lines (57 loc) · 1.9 KB
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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main2 {
static int N, answer;
static int[][] map;
static boolean[][] visited;
static int[] dx = {0, 0, 0, 1, -1};
static int[] dy = {0, 1, -1, 0, 0};
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
map = new int[N][N];
for(int i=0; i<N; i++){
st = new StringTokenizer(br.readLine());
for(int j=0; j<N; j++){
map[i][j] = Integer.parseInt(st.nextToken());
}
}
visited = new boolean[N][N];
answer = Integer.MAX_VALUE;
dfs(0,0);
System.out.println(answer);
br.close();
}
public static void dfs(int level, int sum){
if(level == 3){
answer = Math.min(answer, sum);
return;
}
for(int i=1; i<N-1; i++){
for(int j=1; j<N-1; j++){
int nextSum = sum;
boolean isVisited = false;
for(int d=0; d<5; d++){
if(!visited[i+dx[d]][j+dy[d]]){
nextSum += map[i+dx[d]][j+dy[d]];
} else {
isVisited = true;
break;
}
}
if(!isVisited){
for(int d=0; d<5; d++){
visited[i+dx[d]][j+dy[d]] = true;
}
dfs(level+1, nextSum);
for(int d=0; d<5; d++){
visited[i+dx[d]][j+dy[d]] = false;
}
}
}
}
}
}