P2040 turns on all the lights

Topic background

pmshz playing a benefit (ruo) wisdom (zhi) of the game, the purpose is to open all the lights nine lights, this game stumped pmshz. . .

Title Description

This light is odd (Fan) strange (ren), the tap will switch the status lights and around all four lamps changes. Your task now is to tell pmshz is open to all these lights.

E.g

0  1  1
1  0  0
1  0  1

Tap the middle of the most light [2,2] becomes

0  0  1
0  1  1
1  1  1

Then tap the top left corner lights [1,1] becomes

1  1  1
1  1  1
1  1  1

goal achieved. It requires a minimum of two steps.

Output 2 can be.

Input Format

Nine digits, the format of the input 3 * 3, only one of each of two digital intermediate space, represented by the initial light switching state. (0 for off, 1 on)

Output Format

An integer indicating the minimum number of steps to open all the lights required.

Sample input and output

Input # 1
0 1 1
1 0 0
1 0 1
Output # 1
2

Description / Tips

The problem of water is not water, to see how you consider. . . .

Code

#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;

int a[5][5],ans=10,Mix=0;

void change(int x,int y) {
	a[x][y]=1-a[x][y];
	a[x+1][y]=1-a[x+1][y];
	a[x][y+1]=1-a[x][y+1];
	a[x-1][y]=1-a[x-1][y];
	a[x][y-1]=1-a[x][y-1];
}

void dfs(int k) {
	if(k>ans)
		return;
	int sum=0;
	for(int i=1; i<=3; i++)
		for(int j=1; j<=3; j++)
			sum+=a[i][j];
	if(sum==9) {
		Mix=k-1;
		if(Mix<ans)
			ans=Mix;
	}
	for(int i=1; i<=3; i++)
		for(int j=1; j<=3; j++) {
			change(i,j);
			dfs(k+1);
			change(i,j);
		}
}

int main () {
	for(int i=1; i<=3; i++)
		for(int j=1; j<=3; j++)
			scanf("%d",&a[i][j]);
	dfs(1);
	printf("%d\n",ans);
	return 0;
}

 

Guess you like

Origin www.cnblogs.com/mysh/p/11486013.html