Problem: Example

Input

9
0 0 v
1 0 >
2 0


Output

9

Solution (in CPP):

Solution:
#include<bits/stdc++.h>
#define N 3005
using namespace std;
int F[N][N],ymax,xmax,ans;
int dy[4]={-1,0,1,0};
int dx[4]={0,1,0,-1};

void dfs(int y,int x,int cnt,int dir){
  if(F[y][x]>=0){
    int tmp=F[y][x];
    int ny=y+dy[tmp];
    int nx=x+dx[tmp];
    ans=max(ans,cnt+1);
    if(ny<0||nx<0||ymax<=ny||xmax<=nx)return;
    F[y][x]=-1;
    dfs(ny,nx,cnt+1,tmp);
    F[y][x]=tmp;
    return;
  }
  int ny=y+dy[dir];
  int nx=x+dx[dir];
  if(ny<0||nx<0||ymax<=ny||xmax<=nx)return;
  dfs(ny,nx,cnt,dir);
}

int main(){
  int n,x[N],y[N];
  char d[N];
  map<int,int> X,Y;
  cin>>n;
  for(int i=0;i<n;i++){
    cin>>x[i]>>y[i]>>d[i];
    X[x[i]]=0;
    Y[y[i]]=0;
  }
  int num=0;
  map<int,int>::iterator ite=X.begin();
  while(ite!=X.end()){
    (*ite).second=num;
    num++;
    ite++;
  }
  xmax=num;
  ite=Y.begin();
  num=0;
  while(ite!=Y.end()){
    (*ite).second=num;
    num++;
    ite++;
  }
  ymax=num;
  memset(F,-1,sizeof(F));
  for(int i=0;i<n;i++){
    if(d[i]=='^')F[Y[y[i]]][X[x[i]]]=0;
    if(d[i]=='>')F[Y[y[i]]][X[x[i]]]=1;
    if(d[i]=='v')F[Y[y[i]]][X[x[i]]]=2;
    if(d[i]=='<')F[Y[y[i]]][X[x[i]]]=3;
  }
  for(int i=0;i<n;i++)
    dfs(Y[y[i]],X[x[i]],0,0);
  cout<<ans<<endl;
  return 0;
}