NOI-1.8-17-最好的草-矩阵找最大连接井号-【递归】

17:最好的草

总时间限制: 
10000ms
 
单个测试点时间限制: 
1000ms
 
内存限制: 
65536kB
描述

奶牛Bessie计划好好享受柔软的春季新草。新草分布在R行C列的牧场里。它想计算一下牧场中的草丛数量。

在牧场地图中,每个草丛要么是单个“#”,要么是有公共边的相邻两个“#”。给定牧场地图,计算有多少个草丛。

例如,考虑如下5行6列的牧场地图

.#....
..#...
..#..#
...##.
.#....

这个牧场有5个草丛:一个在第一行,一个在第二列横跨了二、三行,一个在第三行,一个在第四行横跨了四、五列,最后一个在第五行。

输入
第一行包含两个整数R和C,中间用单个空格隔开。
接下来R行,每行C个字符,描述牧场地图。字符只有“#”或“.”两种。(1 <= R, C <= 100 )
输出
输出一个整数,表示草丛数。
样例输入
5 6
.#....
..#...
..#..#
...##.
.#....
样例输出
5


#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <string>
#include <ctype.h>

using namespace std;
char ma[101][101];

int co(int i, int j) {
    if(ma[i+1][j] == '#')   {
        ma[i+1][j] = '.';
        co(i+1, j);
    }
    if(ma[i-1][j] == '#')   {
        ma[i-1][j] = '.';
        co(i-1, j);
    }
    if(ma[i][j+1] == '#')   {
        ma[i][j+1] = '.';
        co(i, j+1);
    }
    if(ma[i][j-1] == '#')   {
        ma[i][j-1] = '.';
        co(i, j-1);
    }
    else{
        return 0;
    }
}

int main()  {

    int a, b;
    scanf("%d%d", &a, &b);
    for(int i = 0; i < a; i++)  {
        for(int j = 0; j < b; j++)  {
            // scanf("%c", &ma[i][j]);
            cin >> ma[i][j];
        }
    }
    int count = 0;
    for(int i = 0; i < a; i++)  {
        for(int j = 0; j < b; j++)  {
            if(ma[i][j] == '#') {
                co(i, j);
                count++;
            }
        }
    }
//    for(int i = 0; i < a; i++)  {
//        for(int j = 0; j < b; j++)  {
//            printf("%c", ma[i][j]);
//        }
//        printf("
");
//    }
    printf("%d
", count);



    return 0;
}

一直对递归有些恐惧,正好用这道题练手

原文地址:https://www.cnblogs.com/QingHuan/p/7113286.html