fork(1) download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. typedef long long ll;
  4. bool visit[1000005];
  5. vector <ll> adj[1000005];
  6. void dfs(ll x)
  7. {
  8. visit[x] = true;
  9. //changed here
  10. for(int i=0;i<adj[x].size();i++)
  11. {
  12. if(visit[adj[x][i]]==false)
  13. dfs(adj[x][i]);
  14. }
  15. }
  16.  
  17. int main()
  18. {
  19. ios::sync_with_stdio(false);
  20. cin.tie(NULL);
  21. ll n,m;
  22. cin>>n>>m;
  23. char ch;
  24. ll k=0,ranjana=0;
  25. char str[n][m];
  26. ll count[n][m];
  27. //vector <ll> adj[n*m+1];
  28. for(ll i=0;i<n;i++)
  29. {
  30. for(ll j=0;j<m;j++)
  31. {
  32. cin>>ch;
  33. str[i][j] = ch;
  34. count[i][j] = k;
  35. k++;
  36. }
  37. }
  38. memset(visit,false,sizeof(visit));
  39. ll val=0;
  40. for(ll i=0;i<n;i++)
  41. {
  42. for(ll j=0;j<m;j++)
  43. {
  44. if(str[i][j]=='S' and i+1 < n)
  45. val = count[i+1][j];
  46. else if(str[i][j]=='N' and i-1 >=0)
  47. val = count[i-1][j];
  48. else if(str[i][j]=='E' and j+1 < m)
  49. val = count[i][j+1];
  50. else if(str[i][j]=='W' and j-1 >= 0)
  51. val = count[i][j-1];
  52.  
  53. adj[count[i][j]].push_back(val);
  54. // Changed here
  55. adj[val].push_back(count[i][j]);
  56. }
  57. }
  58. for(ll i=0;i<n*m ; i++)
  59. {
  60. if(visit[i]==false)
  61. {
  62. dfs(i);
  63. ranjana++;
  64. }
  65. }
  66. cout<<ranjana<<endl;
  67. for(ll i=0;i<n*m;i++)
  68. adj[i].clear();
  69.  
  70. return 0;
  71. }
  72.  
Runtime error #stdin #stdout 0s 39656KB
stdin
Standard input is empty
stdout
Standard output is empty