题解 P1560 【[USACO5.2]蜗牛的旅行Snail Trails】
include <cstdio>
include <iostream>
using namespace std;
const int MAXN = 120; char x; int n,m,y,Ans; char Map[ MAXN + 5 ][ MAXN + 5 ]; bool vis[ MAXN + 5 ][ MAXN + 5 ]; //直接开干,肯定有人跟我一样暴力,勿喷鸭 int tx[ 5 ] = { 0 , 1 , -1 , 0 , 0 }; int ty[ 5 ] = { 0 , 0 , 0 , 1 , -1 }; void dfs( int x , int y , int step , int s ) { Ans = max( Ans , step ); if( s ) { int fx = x + tx[ s ] , fy = y + ty[ s ]; if( fx == 0 || fy == 0 || fx == n + 1 || fy == n + 1 || Map[ fx ][ fy ] == '#' ) goto there; if( vis[ fx ][ fy ] ) return; vis[ fx ][ fy ] = 1; dfs( fx , fy , step + 1 , s ); vis[ fx ][ fy ] = 0; return; } there:; for( int i = 1 ; i <= 4 ; i ++ ) { int fx = x + tx[ i ] , fy = y + ty[ i ]; if( fx == 0 || fy == 0 || fx == n + 1 || fy == n + 1 || Map[ fx ][ fy ] == '#' || vis[ fx ][ fy ] ) continue; vis[ fx ][ fy ] = 1; dfs( fx , fy , step + 1 , i ); vis[ fx ][ fy ] = 0; } }
int main( ) { scanf("%d %d",&n,&m); for( int i = 1 ; i <= n ; i ++ ) for( int j = 1 ; j <= n ; j ++ ) Map[ i ][ j ] = '.'; for( int i = 1 ; i <= m ; i ++ ) { cin >> x; scanf("%d",&y); Map[ y ][ x - 'A' + 1 ] = '#'; } /for( int i = 1 ; i <= n ; i ++ ) { for( int j = 1 ; j <= n ; j ++ ) printf("%c",Map[ i ][ j ]); printf("\n"); }/ vis[ 1 ][ 1 ] = 1; dfs( 1 , 1 , 1 , 0 ); printf("%d",Ans); return 0; }