[关闭]
@Moritz 2019-03-29T08:48:29.000000Z 字数 939 阅读 366

全球变暖

蓝桥杯 蓝桥杯第九届 C++ DFS 所有文稿


两次dfs

  1. /*16'34-17:02*/
  2. #include <iostream>
  3. #include <cmath>
  4. #include <string.h>
  5. using namespace std;
  6. const int maxn=1010;
  7. char island[maxn][maxn];
  8. bool ma[maxn][maxn],m2[maxn][maxn]={false};
  9. int n;
  10. void dfs(int y,int x){
  11. for(int c=-1;c<=1;c++){
  12. for(int r=-1;r<=1;r++){
  13. if (r*c==0&&y+r>=0&&y+r<n&&x+c>=0&&x+c<n){
  14. if (island[y+r][x+c]=='#'&&!ma[y+r][x+c]){
  15. ma[y+r][x+c]=true;
  16. dfs(y+r,x+c);
  17. }
  18. }
  19. }
  20. }
  21. return;
  22. }
  23. int main(){
  24. cin>>n;
  25. memset(ma,false,sizeof(ma));
  26. for(int i=0;i<n;i++){
  27. for(int j=0;j<n;j++){
  28. cin>>island[i][j];
  29. }
  30. }
  31. int cnt=0;
  32. for(int i=0;i<n;i++){
  33. for(int j=0;j<n;j++){
  34. if (island[i][j]=='#'&&!ma[i][j]){
  35. cnt++;
  36. ma[i][j]=true;
  37. dfs(i,j);
  38. }
  39. }
  40. }
  41. for(int i=0;i<n;i++){
  42. for(int j=0;j<n;j++){
  43. if (!ma[i][j]){
  44. for(int c=-1;c<=1;c++){
  45. for(int r=-1;r<=1;r++){
  46. if (r*c==0&&i+r>=0&&i+r<n&&j+c>=0&&j+c<n){
  47. island[i+r][j+c]='.';
  48. }
  49. }
  50. }
  51. }
  52. }
  53. }
  54. cnt=0;
  55. memset(ma,false,sizeof(ma));
  56. for(int i=0;i<n;i++){
  57. for(int j=0;j<n;j++){
  58. if (island[i][j]=='#'&&!ma[i][j]){
  59. cnt++;
  60. ma[i][j]=true;
  61. dfs(i,j);
  62. }
  63. }
  64. }
  65. cout<<cnt;
  66. return 0;
  67. }

2019.3.3

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注