can somebody explain me why does this bfs does not work 
#include<cstdio>
#include<queue>
using namespace std;
char grad[1010][1010];
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};
char smjer[4]={'W','E','N','S'};
queue<pair<int,int> > Q;
int n,m,rj;
void oznaci(int *x,int *y,char dio){
if(dio=='N'){
*x=-1;
*y=0;
}
else if(dio=='S'){
*x=1;
*y=0;
}
else if(dio=='W'){
*x=0;
*y=-1;
}
else if(dio=='E'){
*x=0;
*y=1;
}
}
void BFS(){
while(Q.size()){
int x=Q.front().first;
int y=Q.front().second;
Q.pop();
int pomakx,pomaky;
oznaci(&pomakx,&pomaky,grad[x][y]);
grad[x][y]='Q';
for(int i=0;i<4;i++){
int sx=x+dx[i];
int sy=y+dy[i];
if(sx<0||sx>=n||sy<0||sy>=m) continue;
if(grad[sx][sy]=='Q') continue;
if((grad[sx][sy]==smjer[i])||(dx[i]==pomakx && dy[i]==pomaky)) // mogu li se ikako povezat 2 cvo
Q.push(make_pair(sx,sy));
}
}
}
int main(){
scanf("%d %d",&n,&m);
for(int i=0;i<n;i++) scanf("%s",grad[i]);
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(grad[i][j]!='Q'){
Q.push(make_pair(i,j));
BFS(); rj++;
}
}
}
printf("%d",rj);
return 0;
}