嚴蔚敏3.20

//替換(i,j)及其上下左右同色鄰接點的顏色值
#include <iostream>
#include <time.h>
using namespace std;

int Pic[30][30];

class Position
{
public:
	int x;
	int y;
};
class MyStack
{
public:
	int Top;
	Position Node[100];
	MyStack();
	void Push(int x,int y);
	void Pop();
};
MyStack::MyStack()
{
	Top=0;
}
void MyStack::Push(int x,int y)
{
	Top+=1;
	Node[Top].x=x;
	Node[Top].y=y;
}
void MyStack::Pop()
{
	Top-=1;
}

int Replace(MyStack &by,int x,int y)
{
	if (Pic[x][y]==1)
	{
		by.Push(x,y);
		Pic[x][y]=0;
		if (Pic[x+1][y]==1)
		{
			Replace(by,x+1,y);
		}
		else if (Pic[x-1][y]==1)
		{
			Replace(by,x-1,y);
		}
		else if (Pic[x][y+1]==1)
		{
			Replace(by,x,y+1);
		}
		else if (Pic[x][y-1]==1)
		{
			Replace(by,x,y-1);
		}
		else
		{
			cout<<"替換結束!"<<endl;
			return 1;
		}
	}
	else
	{
		cout<<"不可替換!"<<endl;
		return 0;
	}
}

int main()
{
	for (int i=0;i<10;i++)
	{
		for (int j=0;j<10;j++)
		{
			if ((i==j)&&(i+j>2))
			{
				Pic[i][j]=1;
			}
			else
				Pic[i][j]=0;
			Pic[4][5]=1;
			Pic[5][4]=1;
			cout<<Pic[i][j]<<" ";
		}
		cout<<endl;
	}
	MyStack by;
	if (Replace(by,4,4))
	{	
		cout<<"替換的結果爲:"<<endl;
		for (int i=1;i<=by.Top;i++)
		{
			cout<<by.Node[i].x<<","<<by.Node[i].y<<endl;
		}
	}
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章