2018.8.12字节跳动笔试第一题-看台球迷人数问题-递归小岛问题

题目描述

世界杯开幕式会在球场C举行,球场C的球迷看台可以容纳 M × N 个球迷。在球场售票完成后,现官方想统计此次开幕式一共有多少个球队球迷群体,最大的球队球迷群体有多少人。
经调研发现,球迷群体在选座时有以下特性:

  • 同球队的的球迷群体会选择相邻作为,不同球队的球迷群体会选择不相邻的作为。(注解:相邻包括前后相邻、左右相邻、斜对角相邻。)
  • 给定一个 M × N 的二维球场,0代表该位置没有人,1代表该位置已有球迷,希望输出球队群体个数P,最大的球队群体人数Q。

输入描述

第一行,2个数字,M及N,使用英文逗号分割。
接下来M行,每行N个数字,使用英文逗号分割。

输出描述

一行2个数字,P及Q,使用英文逗号分割。
其中P表示球队群体个数,Q表示最大的球队群体人数

示例

输入

10,10
0,0,0,0,0,0,0,0,0,0
0,0,0,1,1,0,1,0,0,0
0,1,0,0,0,0,0,1,0,1
1,0,0,0,0,0,0,0,1,1
0,0,0,1,1,1,0,0,0,1
0,0,0,0,0,0,1,0,1,1
0,1,1,0,0,0,0,0,0,0
0,0,0,1,0,1,0,0,0,0
0,0,1,0,0,1,0,0,0,0
0,1,0,0,0,0,0,0,0,0

输出

6,8

思路描述

用A来表示球场情况,和A相同大小的B来统计对应位置是否统计过。遍历A,判断某位置是否有球迷,是则根据B来判断该位置的球迷是否已统计过,没有统计过就统计该球迷所在的球迷群体人数。

代码实现

#include <iostream>
#include <cstdio>
#include <sstream>
#include <vector>

using namespace std;

int getAGroup(vector<vector<int> > &A, vector<vector<int> > &B, int i, int j) {
    if (i<0 || j<0 || i>A.size()-1 || j>A[0].size()-1 || B[i][j]==1 || A[i][j]==0)
        return 0;
    else {
        B[i][j] = 1;
        return 1+getAGroup(A, B, i-1, j-1)+getAGroup(A, B, i-1, j)+getAGroup(A, B, i-1, j+1)+getAGroup(A, B, i, j-1)+getAGroup(A, B, i, j+1)+getAGroup(A, B, i+1, j-1)+getAGroup(A, B, i+1, j)+getAGroup(A, B, i+1, j+1);
    }
}

int main()
{
    int M, N, t;
    scanf("%d,%d", &M, &N);
    vector<vector<int> > A(M, vector<int> (N, 0));
    vector<vector<int> > B(M, vector<int> (N, 0));
    for (int i=0;i<M;++i) {
        for (int j=0;j<N-1;++j) {
            scanf("%d,", &t);
            A[i][j] = t;
            B[i][j] = 0;
        }
        scanf("%d", &t);
        A[i][N-1] = t;
        B[i][N-1] = 0;
    }
    int count = 0, max_num = 0;
    for (int i=0;i<M;++i) {
        for (int j=0;j<N;++j) {
            if (A[i][j]==1 && B[i][j]==0) {
                count++;
                int num = getAGroup(A, B, i, j);
                max_num = num>max_num?num:max_num;
            }
        }
    }
    cout << count << "," << max_num;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Asun0204/article/details/81635802