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;
    }
  • 相关阅读:
    Java基础之Java中的泛型
    Oracle基础之分析表
    Java基础之反射机制
    使用vue-cli+webpack搭建vue开发环境
    es6语法
    vue计算属性
    vue模板语法
    jq问题
    原生js-返回顶部
    javascript内置对象
  • 原文地址:https://www.cnblogs.com/rainydays/p/1948683.html
Copyright © 2011-2022 走看看