一个很简单的后退到上一步的思路

主要思路就是把当前局面全部存下来,要回退的时候,直接覆盖上一局面

#include "标头.h"
#include <random>
#include <stack>
#include<time.h>

int curSituation[4][4];
std::stack<int*> regretSituation;

//随机产生一个新的局面
void newSituation()
{
	for (int i = 0; i < 4; ++i)
	{
		for (int j = 0; j < 4; ++j)
		{
			curSituation[i][j] = rand() % 100;
		}
	}
}

//存下旧的局面
void saveOldSituation()
{
	int* oldSituation = new int[16];
	for (int i = 0; i < 4; ++i)
	{
		for (int j = 0; j < 4; ++j)
		{
			oldSituation[i * 4 + j] = curSituation[i][j];
		}
	}
	regretSituation.push(oldSituation);
}

//打印当前局面
void printCurSituation()
{
	std::cout << "当前局面:" << std::endl;
	for (int i = 0; i < 4; ++i)
	{
		std::cout << "    ";
		for (int j = 0; j < 4; ++j)
		{
			std::cout << curSituation[i][j] << " ";
		}
		std::cout << std::endl;
	}
	std::cout << std::endl << std::endl;
}

//后退一步
void rigret()
{
	int* oldSituation = regretSituation.top();
	for (int i = 0; i < 4; ++i)
	{
		for (int j = 0; j < 4; ++j)
		{
			 curSituation[i][j] = oldSituation[i * 4 + j];
		}
	}
	regretSituation.pop();
	delete[] oldSituation;
}

void main()
{
	srand((int)time(0));
	//产生一个初始局面
	newSituation();
	printCurSituation();

	//产生5个新的局面
	int i = 5;
	while (--i)
	{
		saveOldSituation();
		newSituation();
		printCurSituation();
	}

	//后腿一步
	rigret();
	std::cout << "后退了一步" << std::endl;
	printCurSituation();
}


展开阅读全文

没有更多推荐了,返回首页