UVa11581 - Grid Successors(模拟)

本文介绍了一个关于3x3矩阵变换的问题,通过定义特定的变换规则,求解矩阵达到自身不变状态所需的变换次数。文章提供了完整的C++代码实现,并详细解释了输入输出样例及解决思路。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Consider a 3 x 3 grid of numbers g where each cell contains either a 0 or a 1.We define a function f that transforms such a grid: each cell of thegrid f(g) is the sum (modulo 2) of its adjacent cells in g(two cells are considered adjacent if and only if they share a common side).

Furthermore, we define (i)(g) recursivelyas (0)(g) = g and(i+1)(g)  =  f(f (i)(g))(where i  ≥  0).Finally, for any grid h, let kg(h) be the number ofindices i such that h = f (i)(g) (we may have kg(h) = ∞).Given a grid g, your task is to compute the greatest index isuch that kg(f (i)(g)) is finite.

Input begins with the number of test cases on its own line.Each case consists of a blank line followed by three lines of three characters, each either 1 or 0.The j'th characterof the i'th row of the test case is the value in the j'th cellof the i'th row of the grid g.

For each test case, output the greatest index i such thatkg(f (i)(g)) is finite.If there is no such index, output -1.

Sample input

3

111
100
001

101
000
101

000
000
000

Sample output

3
0
-1
题意:一个3x3的矩阵,求经过多少次变换,原矩阵和新矩阵一样。变换是指将相邻的元素(上、下、左、右)相加的和对2取模。

思路:按照题意,求出新矩阵,将原矩阵与新矩阵相比,是否相等,不相等继续变换,直到相等为止

#include <cstdio>
#include <cstring>

using namespace std;

const int MAXN = 3;

int a[MAXN][MAXN], b[MAXN][MAXN];

void input()
{
	char buf[MAXN + 1];
	for (int i = 0; i < MAXN; i++) {
		scanf("%s", buf);
		for (int j = 0; j < MAXN; j++) {
			a[i][j] = buf[j] - '0';
		}
	}
}

void transform()
{
	for (int i = 0; i < MAXN; i++) {
		for (int j = 0; j < MAXN; j++) {
			int sum = 0;
			if (j - 1 >= 0) sum += a[i][j - 1];
			if (i - 1 >= 0) sum += a[i - 1][j];
			if (j + 1 < MAXN) sum += a[i][j + 1];
			if (i + 1 < MAXN) sum += a[i + 1][j];
			
			b[i][j] = sum % 2;
		}
	}
}

void solve()
{
	int ans = 0;
	
	while (1) {
		transform();
		if (memcmp(a, b, sizeof(a)) == 0) break;
		ans++;
		memcpy(a, b, sizeof(b));
	}
	
	printf("%d\n", ans - 1);
}

int main(int argc, char **argv)
{
	#ifndef ONLINE_JUDGE
		freopen("e:\\uva_in.txt", "r", stdin);
	#endif
	
	int cas;
	scanf("%d", &cas);
	while (cas--) {
		input();
		solve();
	}

	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kgduu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值