#include<bits/stdc++.h>
#define M 1005
#define N 55
using namespace std;

void bnf(bool);
void If(bool);

string grid[N],s;
int h,w,p,y,x,dir,cnt,ans;
bool used[M][N][N][4];

int dy[4]={-1,0,1,0};
int dx[4]={0,1,0,-1};

bool get_if(){
  bool res=false;

  if(s[p]=='~')res=!res,p++;
  
  if(s[p]=='N'&&dir==0)res=!res;
  
  if(s[p]=='E'&&dir==1)res=!res;
  
  if(s[p]=='S'&&dir==2)res=!res;
  
  if(s[p]=='W'&&dir==3)res=!res;
  
  if(s[p]=='C'&&grid[y+dy[dir]][x+dx[dir]]=='#')res=!res;
  
  if(s[p]=='T')res=!res;
  
  p++;
  return res;
}

void move_ai(bool flag){
  
  if(flag){
    cnt++;

    if(s[p]=='^'){
      int ny=y+dy[dir],nx=x+dx[dir];
      if(grid[ny][nx]!='#')y=ny,x=nx;
    }
    
    if(s[p]=='v'){
      int ny=y-dy[dir],nx=x-dx[dir];
      if(grid[ny][nx]!='#')y=ny,x=nx;
    }
    
    if(s[p]=='<')dir=(dir+3)%4;
    
    if(s[p]=='>')dir=(dir+1)%4;
    
  }
  
  p++;
  
  if(!ans&&grid[y][x]=='g')ans=cnt;
}

void While(bool flag){
  int prev=++p;

  while(1){
    bool r=get_if();
    
    while(s[p]!='}'){
      if(s[p]=='{') While(flag&r);
      else if(s[p]=='[') If(flag&r);
      else move_ai(flag&r);
    }

    int temp=p;
    p=prev;
    
    int r1=get_if();

    if(!r1||!r||!flag){
      p=temp;
      break;
    }
    
    if(used[p][y][x][dir]){
      cout<<(ans?ans:-1)<<endl;
      exit(0);
    }
    used[p][y][x][dir]=true;

    p=prev;
  }
  
  p++;
}

void If(bool flag){
  p++;

  bool r=get_if();
  
  while(s[p]!=']'){
    if(s[p]=='{') While(flag&r);
    else if(s[p]=='[') If(flag&r);
    else move_ai(flag&r);
  }
  
  p++;
}
 
void bnf(bool flag){
  
  while(s[p]!='x'){
    
    if(s[p]=='{') While(flag);
    else if(s[p]=='[') If(flag);
    else move_ai(flag);
    
  }
  
}

int main(){
  
  cin>>h>>w;
  
  for(int i=0;i<h;i++){
    cin>>grid[i];
    
    for(int j=0;j<w;j++)
      if(grid[i][j]=='s')y=i,x=j;
     
  }
  
  cin>>s;  s+='x';
  
  bnf(true);
  
  cout<<(ans?ans:-1)<<endl;
  return 0;
}