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 f (i)(g) recursivelyas f (0)(g) = g andf (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;
}