1+ import java .io .*;
2+ import java .util .*;
3+
4+ public class Main {
5+ static Map <Character , Integer > MOLA ;
6+ static int [] dx = {1 , 0 };
7+ static int [] dy = {0 , 1 };
8+ static int [][][] dp ;
9+ static int n , ans ;
10+ static char [][] map ;
11+ static BufferedReader br = new BufferedReader (new InputStreamReader (System .in ));
12+ public static void main (String [] args ) throws Exception {
13+ inputSetting ();
14+
15+ System .out .println (recur (0 , 0 , MOLA .getOrDefault (map [0 ][0 ], 0 )));
16+ }
17+
18+ static int recur (int x , int y , int pre ){
19+ if (x == n - 1 && y == n - 1 ) return 0 ;
20+ if (dp [pre ][x ][y ] != -1 ) return dp [pre ][x ][y ];
21+ int nx , ny , now , rot ;
22+
23+ rot = 0 ;
24+ for (int i = 0 ; i < 2 ; i ++) {
25+ nx = x + dx [i ];
26+ ny = y + dy [i ];
27+
28+ if (nx < 0 || n <= nx || ny < 0 || n <= ny ) continue ;
29+
30+ now = MOLA .getOrDefault (map [nx ][ny ], 0 );
31+
32+ if (now == 4 && pre == 3 ) rot = Math .max (rot , recur (nx , ny , 0 ) + 1 );
33+ else if (pre + 1 == now || now == 1 ) rot = Math .max (rot ,recur (nx , ny , now ));
34+ else rot = Math .max (rot ,recur (nx , ny ,0 ));
35+
36+ }
37+ return dp [pre ][x ][y ] = rot ;
38+ }
39+
40+ static void inputSetting () throws Exception {
41+ n = Integer .parseInt (br .readLine ());
42+ map = new char [n ][n ];
43+ MOLA = new HashMap <>();
44+ dp = new int [5 ][n ][n ];
45+
46+ for (int i = 0 ; i < 5 ; i ++){
47+ for (int j = 0 ; j < n ; j ++) Arrays .fill (dp [i ][j ], -1 );
48+ }
49+
50+ for (int i = 0 ; i < n ; i ++) map [i ] = br .readLine ().toCharArray ();
51+ MOLA .put ('M' , 1 );
52+ MOLA .put ('O' , 2 );
53+ MOLA .put ('L' , 3 );
54+ MOLA .put ('A' , 4 );
55+ }
56+ }
0 commit comments