poj2965

dfs,O(2^16)

 

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;

bool map[4][4];
int ans[16];

void init()
{
	int i, j;

	for (i = 0; i < 4; i++)
	{
		for (j = 0; j < 4; j++)
		{
			char ch;
			cin >> ch;
			if (ch == '-')
				map[i][j] = true;
			else
				map[i][j] = false;
		}
		getchar();
	}
}

void operate(int x, int y)
{
	if (x < 0 || y < 0 || x > 3 || y > 3)
		return;
	map[x][y] = !map[x][y];
}

void turn(int pos)
{
	ans[pos] = !ans[pos];
	int x = pos / 4;
	int y = pos % 4;
	int i;
	operate(x, y);
	for (i = 1; i < 4; i++)
	{
		operate(x + i, y);
		operate(x, y + i);
		operate(x - i, y);
		operate(x, y - i);
	}
}

bool finished()
{
	int tot = 0;
	int i;
	for (i = 0; i < 16; i++)
		tot += map[i / 4][i % 4];
	return (tot == 16);
}

void output()
{
	int i;
	for (i = 0; i < 16; i++)
	{
		if (ans[i])
			printf("%d %d\n", i / 4 + 1, i % 4 + 1);
	}
}

void dfs(int pos, int step)
{
	if (finished())
	{
		cout << step << endl;
		output();
		exit(0);
		return;
	}
	if (pos >= 16)
		return;
	dfs(pos + 1, step);
	turn(pos);
	dfs(pos + 1, step + 1);
	turn(pos);//这句忘了写,导致错误
}

int main()
{
	//freopen("D:\\t.txt", "r", stdin);
	init();
	dfs(0, 0);

	return 0;
}
posted @ 2011-02-01 14:27  金海峰  阅读(684)  评论(0编辑  收藏  举报