这是数据结构老师布置的实验A,题目描述如下:
在一个矩形网格中,每一个格子的颜色或者为白色或者为黑色。任意或上、或下、或左、或右相邻同为黑色的格子组成一个家族。家族中所有格子的数量反映家族的大小。要求找出最大家族的家族大小(组成最大家族的格子的数量)。例如下图中最大家族的格子数量为 8。
要求:
1、网格用二维数组表示。
2、数组中的元素的值随机产生,分别用0和1表示白格子和黑格子。
3、算法运行结果为最大家族的家族大小。
代码实现:
// 黑白格问题.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
#include "pch.h"
#include <iostream>
#include<cstdio>
#include<ctime>
#include<algorithm>
#include<vector>
using namespace std;
vector<vector<int>> board;//黑白格
vector<vector<int>> temp;//黑白格的备份
vector<vector<bool>> vis;//表示该元素是否被查询过
int directory[4][2] = { {0,1},{1,0},{0,-1},{-1,0} };//四个方向
//产生黑白格
void initialBoard(int HEIGHT)
{
for (int i = 0; i < HEIGHT; i++)
{
vector<int> temp;
for (int j = 0; j < HEIGHT; j++)
{
temp.push_back(rand() % 2);
}
board.push_back(temp);
}
for (int i = 0; i < HEIGHT; i++)
{
vector<int> tmp;
vector<bool> t;
for (int j = 0; j < HEIGHT; j++)
{
tmp.push_back(board[i][j]);
t.push_back(false);
}
temp.push_back(tmp);
vis.push_back(t);
}
}
bool isLeap(int x, int y, int HEIGHT)//该位置元素是否越界
{
return x >= 0 && x < HEIGHT&&y >= 0 && y < HEIGHT;
}
int count(int x, int y, int HEIGHT)//查询该点的连接点的个数
{
vis[x][y] = true;
int ans = 0;
for (int i = 0; i < 4; i++)
{
int nx = x + directory[i][0];
int ny = y + directory[i][1];
if (!isLeap(nx, ny, HEIGHT) || temp[nx][ny] == 0 || vis[nx][ny])
continue;
else
{
ans += count(nx, ny, HEIGHT);
}
}
ans++;
return ans;
}
void printFormatLy(int j, int number, int HEIGHT)
{
cout << number;
if (j == HEIGHT - 1)
cout << endl;
else
{
if (number >= 10)
cout << " ";
else
cout << " ";
}
}
void clearVis(int HEIGHT)//清除访问痕迹,为下一个点做准备
{
for (int m = 0; m < HEIGHT; m++)
for (int n = 0; n < HEIGHT; n++)
vis[m][n] = false;
}
int printBoard(int HEIGHT)//输出分类后的黑白格,并返回最大家族值
{
int maxResult = 0;
for (int i = 0; i < HEIGHT; i++)
for (int j = 0; j < HEIGHT; j++)
{
int number;
if (board[i][j] == 1)
{
number = count(i, j, HEIGHT);
maxResult = max(maxResult, number);
printFormatLy(j, number, HEIGHT);
}
else
{
printFormatLy(j, 0, HEIGHT);
}
clearVis(HEIGHT);
}
return maxResult;
}
int main()
{
srand(time(0));
int HEIGHT;
cout << "输入大小(>=5) ";
cin >> HEIGHT;
initialBoard(HEIGHT);//产生黑白格
cout << "MAX: " << printBoard(HEIGHT) << endl;
}
实验结果: