|
| 1 | +import java.io.BufferedReader; |
| 2 | +import java.io.InputStreamReader; |
| 3 | +import java.io.IOException; |
| 4 | +import java.util.ArrayList; |
| 5 | +import java.util.LinkedList; |
| 6 | +import java.util.Queue; |
| 7 | +import java.util.StringTokenizer; |
| 8 | + |
| 9 | +public class Main { |
| 10 | + |
| 11 | + static int N,M; |
| 12 | + static int arr[][]; |
| 13 | + static int dx[] = {-1,1,0,0}; |
| 14 | + static int dy[] = {0,0,-1,1}; |
| 15 | + static boolean visited[][]; |
| 16 | + static int answer = Integer.MIN_VALUE; |
| 17 | + |
| 18 | + public static void main(String[] args) throws IOException { |
| 19 | + |
| 20 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 21 | + |
| 22 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 23 | + |
| 24 | + N = Integer.parseInt(st.nextToken()); |
| 25 | + |
| 26 | + M = Integer.parseInt(st.nextToken()); |
| 27 | + |
| 28 | + arr = new int[N][M]; |
| 29 | + |
| 30 | + for(int i =0; i<N; i++) { |
| 31 | + st = new StringTokenizer(br.readLine()); |
| 32 | + for(int j =0; j<M; j++) { |
| 33 | + arr[i][j] = Integer.parseInt(st.nextToken()); |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + visited = new boolean[N][M]; |
| 38 | + for(int i =0; i<N; i++) { |
| 39 | + for(int j =0; j<M; j++) { |
| 40 | + visited[i][j] = true; |
| 41 | + dfs(i,j, arr[i][j], 1); |
| 42 | + visited[i][j]= false; |
| 43 | + } |
| 44 | + } |
| 45 | + System.out.println(answer); |
| 46 | + } |
| 47 | + |
| 48 | + static void dfs(int x, int y, int sum, int count) { |
| 49 | + |
| 50 | + if(count ==4) { |
| 51 | + answer = Math.max(sum, answer); |
| 52 | + return; |
| 53 | + } |
| 54 | + |
| 55 | + for(int i = 0; i<4; i++) { |
| 56 | + int nowx = x +dx[i]; |
| 57 | + int nowy = y + dy[i]; |
| 58 | + |
| 59 | + if(nowx >=0 && nowx <N && nowy >=0 && nowy <M) { |
| 60 | + if(!visited[nowx][nowy]) { |
| 61 | + |
| 62 | + if(count ==2) { |
| 63 | + visited[nowx][nowy] = true; |
| 64 | + dfs(x,y, sum+arr[nowx][nowy], count+1); |
| 65 | + visited[nowx][nowy] = false; |
| 66 | + } |
| 67 | + |
| 68 | + visited[nowx][nowy] = true; |
| 69 | + dfs(nowx, nowy, sum+arr[nowx][nowy], count+1); |
| 70 | + visited[nowx][nowy]= false; |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + } |
| 75 | + } |
| 76 | +} |
0 commit comments