题目描述:
世界杯开幕式会在球场C举行,球场C的球迷看台可以容纳M*N个球迷。在球场售票完场后,现官方想统计此次开幕式一共有多少个球队球迷群体,最最大的球队球迷群体有多少人。经调研发现,球迷群体在选座时有一下特性:
- 同球队的球迷群体会选择相邻座位
- 不同球队的球迷群体会选择不相邻的座位。
注解:相邻包括前后相邻/左右相邻/斜对角相邻。
给定一个M*N的二维球场,0代表该位置没有坐人,1代表该位置已有球迷,希望输出球队群体个数P,最大的球队群体人数Q。
输入描述:
第一行,2个数字,M和N,使用英文逗号分割;接下来M行,每行N的数字,使用英文逗号分割;
输出描述:
一行,2个数字,P及Q,使用英文逗号分割;其中,P表示球队群体的个数,Q表示最大的球队群体人数
思路分析:
本题可以利用深度优先搜索来完成,然后利用递归方法来寻找同一个球队的球迷,并且将已经访问过的位置进行置“-1”,目的是不要重复搜索;
代码如下所示:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
//字符串分割函数
std::vector<std::string> split(std::string str, std::string pattern){
std::string::size_type pos;
std::vector<std::string> result;
str += pattern;//扩展字符串以方便操作
int size = str.size();
for (int i = 0; i<size; i++){
pos = str.find(pattern, i);
if (pos<size){
std::string s = str.substr(i, pos - i);
result.push_back(s);
i = pos + pattern.size() - 1;
}
}
return result;
}
static int num = 0;//用于记录同一球队的观众的个数
static int DFS(vector<vector<int>>&matrix, int m, int n) {
if (m < 0 || n < 0) return 0;
if (m >= matrix.size() || n >= matrix[0].size()) return 0;
if (matrix[m][n] == 1){
matrix[m][n] = -1;
num++;
}
else{
return 0;
}
DFS(matrix, m + 1, n);
DFS(matrix, m + 1, n + 1);
DFS(matrix, m + 1, n - 1);
DFS(matrix, m, n + 1);
DFS(matrix, m, n - 1);
DFS(matrix, m - 1, n - 1);
DFS(matrix, m - 1, n);
DFS(matrix, m - 1, n + 1);
return num;
}
int main(int argc, char** argv){
std::string str;
int M, N;
//int dx[] = {-1,-1,-1,0,0,1,1,1};
//int dy[] = {-1,0,1,-1,1,-1,0,1};
getline(std::cin, str);
std::vector<std::string> result = split(str, ",");
M = atoi(result[0].c_str());
N = atoi(result[1].c_str());
//cout << "M:" << M << " " << "N:" << N << endl;
vector<vector<int>> matrix;
vector<int> matrix_;
string ss;
for (int i = 0; i < M; i++) {
getline(cin, ss);
vector<string> temp = split(ss, ",");
for (int j = 0; j < N; j++) {
matrix_.push_back(atoi(temp[j].c_str()));
}
matrix.push_back(matrix_);
matrix_.clear();
}
int number = 0;
int max_per = 0;
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
int x = DFS(matrix, i, j);
if (x != 0){
num = 0;
number++;
}
max_per = max(x, max_per);
}
}
cout << number << "," << max_per << endl;
system("pause");
return 0;
}
本地IDE结果如下所示: