22import java .util .*;
33
44public class Main {
5- static final int MIN = -1000000 ;
6- static int n , m , ans ;
5+ final static int MIN = -100000000 ;
6+ static int [] dx = {0 , 1 , 0 };
7+ static int [] dy = {1 , 0 , -1 };
8+ static int n , m ;
79 static int [][] map ;
810 static int [][][] dp ;
9- static int [] dx = {1 , 0 , 0 };
10- static int [] dy = {0 , -1 , 1 };
1111 static StringTokenizer st ;
1212 static BufferedReader br = new BufferedReader (new InputStreamReader (System .in ));
13- static BufferedWriter bw = new BufferedWriter (new OutputStreamWriter (System .out ));
14-
1513 public static void main (String [] args ) throws Exception {
16- input ();
17- System .out .println (recur (0 , 0 , 0 ) + map [0 ][0 ]);
14+ preSetting ();
15+
16+ for (int i = 0 ; i < 3 ; i ++) {
17+ dp [i ][0 ][0 ] = recur (i , 0 , 0 ) + map [0 ][0 ];
18+ }
19+ System .out .println (Math .max (Math .max (dp [0 ][0 ][0 ], dp [1 ][0 ][0 ]), dp [2 ][0 ][0 ]));
1820 }
1921
20- static void input () throws Exception {
21- st = new StringTokenizer (br .readLine ());
22+ static int recur (int d , int x , int y ){
23+ if (x == n - 1 && y == m - 1 ) return 0 ;
24+ if (dp [d ][x ][y ] != -1 ) return dp [d ][x ][y ];
25+
26+ int nx , ny ;
27+ int rot = MIN ;
28+ for (int i = 0 ; i < 3 ; i ++){
29+ nx = x + dx [i ];
30+ ny = y + dy [i ];
31+
32+ if (isImpossible (d , i , nx , ny )) continue ;
33+ rot = Math .max (rot , recur (i , nx , ny ) + map [nx ][ny ]);
34+ }
35+ return dp [d ][x ][y ] = rot ;
36+ }
2237
38+ static boolean isImpossible (int d , int nd , int nx , int ny ){
39+ if (nx < 0 || ny < 0 || n <= nx || m <= ny ) return true ;
40+ if (d == 0 && nd == 2 || d == 2 && nd == 0 ) return true ;
41+ return false ;
42+ }
43+
44+ static void preSetting () throws Exception {
45+
46+ st = new StringTokenizer (br .readLine ());
2347 n = Integer .parseInt (st .nextToken ());
2448 m = Integer .parseInt (st .nextToken ());
2549
2650 map = new int [n ][m ];
27- dp = new int [n ][ m ][ 3 ];
28- for (int i = 0 ; i < n ; i ++) {
51+ dp = new int [3 ][ n ][ m ];
52+ for (int i = 0 ; i < n ; i ++){
2953 st = new StringTokenizer (br .readLine ());
3054
31- for (int j = 0 ; j < m ; j ++) {
55+ for (int j = 0 ; j < m ; j ++){
3256 map [i ][j ] = Integer .parseInt (st .nextToken ());
33- Arrays .fill (dp [i ][j ], MIN );
3457 }
3558 }
36- }
37-
38- static int recur (int d , int r , int c ){
39- if (r == n - 1 && c == m - 1 ) return 0 ;
4059
41- if (dp [r ][c ][d ] != MIN ) return dp [r ][c ][d ];
42- int nx , ny ;
43- int rot = MIN ;
4460 for (int i = 0 ; i < 3 ; i ++){
45- nx = r + dx [i ];
46- ny = c + dy [i ];
47-
48- if (nx < 0 || n <= nx || ny < 0 || m <= ny ) continue ;
49- if ((d == 1 && i == 2 ) || (d == 2 && i == 1 )) continue ;
50-
51- rot = Math .max (rot , recur (i , nx , ny ) + map [nx ][ny ]);
61+ for (int j = 0 ; j < n ; j ++) Arrays .fill (dp [i ][j ], -1 );
5262 }
53-
54- return dp [r ][c ][d ] = rot ;
5563 }
56- }
64+ }
0 commit comments