@@ -14,6 +14,42 @@ use superslice::*;
1414
1515fn main ( ) {
1616 input ! {
17+ h: usize , w: usize ,
18+ c: [ Chars ; h] ,
19+ }
20+
21+ let mut max_length = 0_i64 ;
22+ for ( y, x) in iproduct ! ( 0 ..h, 0 ..w) {
23+ if c[ y] [ x] != '#' {
24+ max_length = std:: cmp:: max ( max_length, dfs ( & c, & vec ! [ vec![ false ; w] ; h] , ( y, x) , ( y, x) , 0 ) . unwrap_or ( 0 ) )
25+ }
26+ }
27+
28+ println ! ( "{}" , if max_length >= 3 { max_length } else { -1 } )
29+ }
1730
31+ fn dfs ( graph : & Vec < Vec < char > > , visited : & Vec < Vec < bool > > , start : ( usize , usize ) , cur : ( usize , usize ) , length : i64 ) -> Option < i64 > {
32+ let mut cloned_visited = visited. clone ( ) ;
33+ if cloned_visited[ cur. 0 ] [ cur. 1 ] {
34+ if cur. 0 == start. 0 && cur. 1 == start. 1 {
35+ return Some ( length)
36+ }
37+ return None
38+ }
39+ cloned_visited[ cur. 0 ] [ cur. 1 ] = true ;
40+
41+ let mut max_length = 0 ;
42+ if cur. 0 > 0 && graph[ cur. 0 -1 ] [ cur. 1 ] != '#' {
43+ max_length = std:: cmp:: max ( max_length, dfs ( graph, & cloned_visited, start, ( cur. 0 -1 , cur. 1 ) , length + 1 ) . unwrap_or ( 0 ) )
44+ }
45+ if cur. 1 < graph[ 0 ] . len ( ) - 1 && graph[ cur. 0 ] [ cur. 1 + 1 ] != '#' {
46+ max_length = std:: cmp:: max ( max_length, dfs ( graph, & cloned_visited, start, ( cur. 0 , cur. 1 + 1 ) , length + 1 ) . unwrap_or ( 0 ) )
47+ }
48+ if cur. 0 < graph. len ( ) - 1 && graph[ cur. 0 +1 ] [ cur. 1 ] != '#' {
49+ max_length = std:: cmp:: max ( max_length, dfs ( graph, & cloned_visited, start, ( cur. 0 + 1 , cur. 1 ) , length + 1 ) . unwrap_or ( 0 ) )
50+ }
51+ if cur. 1 > 0 && graph[ cur. 0 ] [ cur. 1 - 1 ] != '#' {
52+ max_length = std:: cmp:: max ( max_length, dfs ( graph, & cloned_visited, start, ( cur. 0 , cur. 1 - 1 ) , length + 1 ) . unwrap_or ( 0 ) )
1853 }
54+ return Some ( max_length)
1955}
0 commit comments