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