zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    C++学习网址
    python学习网址
    python之raw_input()函数
    APP营销模式
    计划任务
    多线程
    Spring Aware
    事件(Application Event)
    Spring 的AOP
    Java配置
  • 原文地址:https://www.cnblogs.com/rainydays/p/1948683.html
Copyright © 2011-2022 走看看