fork(5) download
  1. #include<iostream>
  2. #include<cstring>
  3. #include<cstdio>
  4.  
  5. using namespace std;
  6.  
  7. int flag[110][110],row,column;
  8. char grid[110][110];
  9.  
  10. void floodfill(int i, int j);
  11.  
  12. int main()
  13. {
  14. //Loop variable
  15. int i,j,cnt;
  16. cnt = 0;
  17. //Set 'flag' 2D array by zero. to use memset() function you have to include <cstring> or <string.h>
  18. memset(flag, 0, sizeof(flag));
  19.  
  20. //Input number of Row and full 2D array
  21. cin>>row>>column;
  22. getchar();
  23. for(i=0; i<row; i++)
  24. {
  25. for(j=0; j<column; j++)
  26. scanf("%c", &grid[i][j]);
  27. getchar();
  28. }
  29. //Input end
  30.  
  31. //Traverse 2D array
  32. for(i=0; i<row; i++)
  33. {
  34. for(j=0; j<column; j++)
  35. {
  36. if(grid[i][j]=='.' && flag[i][j]==0)
  37. {
  38. cnt++;
  39. floodfill(i,j);
  40. }
  41. }
  42. }
  43.  
  44. cout<<"Number of colored region is: "<<cnt<<endl<<endl;
  45. cout<<"New 2D array is:"<<endl<<endl;
  46.  
  47. for(i=0; i<row; i++)
  48. {
  49. for(j=0; j<column; j++)
  50. {
  51. cout<<grid[i][j];
  52. }
  53. cout<<endl;
  54. }
  55.  
  56.  
  57. return 0;
  58. }
  59.  
  60.  
  61. void floodfill(int i, int j)
  62. {
  63. //Base case
  64. if(i<0 || j<0 || i>row-1 || j>column-1)
  65. return;
  66.  
  67. if(grid[i][j]=='.' && flag[i][j]==0)
  68. {
  69. flag[i][j]=1;
  70. grid[i][j]='+';
  71.  
  72. floodfill(i+1,j);
  73. floodfill(i-1,j);
  74. floodfill(i,j+1);
  75. floodfill(i,j-1);
  76. floodfill(i+1,j+1);
  77. floodfill(i+1,j-1);
  78. floodfill(i-1,j+1);
  79. floodfill(i-1,j-1);
  80. }
  81.  
  82. }
  83.  
Success #stdin #stdout 0s 3532KB
stdin
12 25
@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@*************@@@@@@
@@@@@@*....*     ..@@@@@@
@@@@@@*....*   ....@@@@@@
@.@@@@*....*      .@@@@@@
@@@@@@*....********@@..@@
@@@@@@*...........*@@@...
@@@@@@*...........*@@@..@
@@@@@@*************@@@@.@
@@@@@@@@@.....@@@@@@@@@@@
@@@@@@@@@.....@@@@@@@@@@@
stdout
Number of colored region is: 5

New 2D array is:

@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@*************@@@@@@
@@@@@@*++++*     ++@@@@@@
@@@@@@*++++*   ++++@@@@@@
@+@@@@*++++*      +@@@@@@
@@@@@@*++++********@@++@@
@@@@@@*+++++++++++*@@@+++
@@@@@@*+++++++++++*@@@++@
@@@@@@*************@@@@+@
@@@@@@@@@+++++@@@@@@@@@@@
@@@@@@@@@+++++@@@@@@@@@@@