CSP-201512-2-消除类游戏
解题思路
-  
输入棋盘大小和颜色: 首先,程序从标准输入读取两个整数
n和m,分别代表棋盘的行数和列数。然后,程序读取接下来的n行输入,每行包含m个整数,代表棋盘上每个方格中的棋子颜色。 -  
初始化: 代码中使用了
vector<vector<int>>来存储棋盘的状态。还定义了一个结构体MyPoint用于表示棋子的位置,以及一个pointList向量存储将要被消除的棋子的位置。 -  
横向检查: 程序通过两层循环遍历棋盘的每一行。它比较当前棋子与上一个棋子的颜色。如果它们的颜色不同,程序会检查是否有连续三个或更多相同颜色的棋子(通过变量
constantTimes来记录)。如果有,将这些棋子的位置添加到pointList中;如果没有连续三个颜色相同的棋子,则需要重置lastNum,constantTimes和childPointList。如果颜色相同,则增加constantTimes的值,并将当前棋子的位置添加到childPointList中以便进一步处理。 -  
纵向检查: 类似于横向检查,但这次是按列来遍历棋盘。对于每一列,程序检查连续的相同颜色的棋子,并在发现三个或更多连续相同颜色的棋子时,将它们的位置添加到
pointList。 -  
消除棋子: 遍历
pointList中存储的所有位置,并将这些位置上的棋子在棋盘上标记为0,代表这些棋子已经被消除。 
完整代码
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct MyPoint
{
	int x, y;
};
vector<MyPoint>pointList;
int main() {
	int row, col;
	cin >> row >> col;
	vector<vector<int>>chessBoard(row, vector<int>(col));
	for (auto& it : chessBoard) {
		for (auto& jt : it) {
			cin >> jt;
		}
	}
	// 横向遍历
	for (int i = 0; i < row; i++)
	{
		int constantTimes = 1, lastNum = -1;
		vector<MyPoint>childPointList;
		for (int j = 0; j < col; j++)
		{
			if (chessBoard[i][j] != lastNum) // 与前一个数字不同或者是本行的最后一个元素
			{
				// 判断能否消除
				if (constantTimes >= 3)
				{					
					for (auto& it : childPointList) { // 将消除的点插入子集
						MyPoint t = it;
						pointList.push_back(t);
					}
				}
				lastNum = chessBoard[i][j]; // 更新上一个数字到lastNum
				constantTimes = 1; // 重置连续次数
				childPointList.clear(); // 清空以前的子集
				MyPoint t{ i,j }; // 把当前点加入子集
				childPointList.push_back(t);
			}
			else // 和上一个数字相同
			{
				constantTimes++; // 连续次数+1
				MyPoint t{ i,j }; // 把当前点加入子集
				childPointList.push_back(t);
			}
		
			if (j == col - 1)
			{
				// 判断能否消除
				if (constantTimes >= 3)
				{
					for (auto& it : childPointList) { // 将消除的点插入子集
						MyPoint t = it;
						pointList.push_back(t);
					}
				}
			}
		}
	}
	// 纵向遍历
	for (int i = 0; i < col; i++)
	{
		int constantTimes = 1, lastNum = -1;
		vector<MyPoint>childPointList;
		for (int j = 0; j < row; j++)
		{
			if (chessBoard[j][i] != lastNum)
			{
				if (constantTimes >= 3) 
				{
					for (auto& it : childPointList) { 
						MyPoint t = it;
						pointList.push_back(t);
					}
				}
				lastNum = chessBoard[j][i]; 
				constantTimes = 1;
				childPointList.clear();
				MyPoint t{ j,i };
				childPointList.push_back(t);
			}
			else 
			{
				constantTimes++;
				MyPoint t{ j,i };
				childPointList.push_back(t);
			}
			if (j == row - 1)
			{
				// 判断能否消除
				if (constantTimes >= 3)
				{
					for (auto& it : childPointList) { // 将消除的点插入子集
						MyPoint t = it;
						pointList.push_back(t);
					}
				}
			}
		}
	}
	for (auto& it : pointList)
	{
		chessBoard[it.x][it.y] = 0;
	}
	for (auto& it : chessBoard) {
		for (auto& jt : it) {
			cout << jt << " ";
		}
		cout << endl;
	}
	return 0;
}
 




















