fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int N=1005;
  5. int n, m, a[N][N], ans;
  6. bool vst[N][N];
  7.  
  8. int di[4]={-1, 0, 1, 0};
  9. int dj[4]={0, 1, 0, -1};
  10.  
  11. bool inside(int i, int j) //hàm kiểm tra ô (i, j) có nằm trong ma trận hay không
  12. {
  13. return i>0 && i<=n && j>0 && j<=m;
  14. }
  15.  
  16. void bfs(int u, int v)
  17. {
  18. queue<pair<int, int>> q;
  19. q.push({u, v});
  20. vst[u][v]=1;
  21. while(!q.empty()){
  22. int i=q.front().first, j=q.front().second;
  23. q.pop();
  24. for(int k=0;k<4;++k){
  25. int ni=i+di[k], nj=j+dj[k];
  26. if(inside(ni, nj) && !vst[ni][nj] && a[ni][nj]==1){
  27. vst[ni][nj]=1;
  28. q.push({ni, nj});
  29. }
  30. }
  31. }
  32. }
  33.  
  34. signed main()
  35. {
  36. ios::sync_with_stdio(0);
  37. cin.tie(0); cout.tie(0);
  38.  
  39. cin >> n >> m;
  40. for(int i=1;i<=n;++i){
  41. for(int j=1;j<=m;++j){
  42. cin >> a[i][j];
  43. }
  44. }
  45.  
  46. for(int i=1;i<=n;++i){
  47. for(int j=1;j<=m;++j){
  48. if(!vst[i][j] && a[i][j]==1){
  49. ++ans;
  50. bfs(i, j);
  51. }
  52. }
  53. }
  54.  
  55. cout << ans;
  56. return 0;
  57. }
  58.  
Success #stdin #stdout 0.01s 5324KB
stdin
Standard input is empty
stdout
Standard output is empty