zoukankan      html  css  js  c++  java
  • 一道简单的回溯搜索题

    在一个4*4的小方格(如图所示)中放置8个*号,使得每行每列放且
    仅放两个*号。
    ┌─┬─┬─┬─┐
    │*│*│ │ │
    ├─┼─┼─┼─┤
    │*│ │*│ │
    ├─┼─┼─┼─┤
    │ │*│ │*│
    ├─┼─┼─┼─┤
    │ │ │*│*│
    └─┴─┴─┴─┘
    求出所有的基本解。

    #include <iostream>
    using namespace std;
    
    
    const int N = 4;
    int selected[N][N];
    int colCoins[N]; //记录每列当前的硬币数量
    int gCount = 0;
    void Print()
    {
    	cout << "第" << gCount << "组" << endl;
    	for (int i = 0;i<N;i++)
    	{
    		for (int j = 0;j<N;j++)
    		{
    			cout << selected[i][j] << " ";
    		}
    		cout << endl;
    	}
    	cout << endl << endl;
    	gCount++;
    
    }
    void Initialize()
    {
    	for (int i = 0;i<N;i++)
    	{
    		for (int j = 0;j<N;j++)
    		{
    			selected[i][j] = 0;
    		}
    		colCoins[i] = 0;
    	}
    
    }
    
    void Go(int row)
    {
    	if (row == N) //得到了一个可行解,输出可行解
    	{
    		Print();
    		return;
    	}
    	for (int i = 0;i<N;i++)
    	{
    		for (int j = i+1;j<N;j++)
    		{
    			if (colCoins[i] < 2 && colCoins[j] < 2) //这两个位置可以放置硬币
    			{
    				colCoins[i]++;colCoins[j]++;
    				selected[row][i] = selected[row][j] = 1;
    				Go(row + 1);
    				colCoins[i]--;colCoins[j]--;               //回溯
    				selected[row][i] = selected[row][j] = 0;
    			}
    		}
    	}
    }
    void main()
    {
    //	Initialize();
    	Go(0);
    	cout << "共有" << gCount << "组解"<<endl;
    
    }
  • 相关阅读:
    本周总结
    本周总结
    本周总结
    本周总结
    性能分析(4)
    大型网站高性能架构
    第二天大数据清洗
    性能分析(2)
    六大质量属性——性能分析(1)
    java设计模式9-代理模式
  • 原文地址:https://www.cnblogs.com/speedmancs/p/1715510.html
Copyright © 2011-2022 走看看