zoukankan      html  css  js  c++  java
  • 【IT面试题005】八皇后

    /*
     8皇后
    */
    
    #include "stdafx.h"
    
    #include <iostream>
    #include <string>
    #include <vector>
    using namespace std;
    
    
    const int MAX_ELEMENT = 1000;
    int solution[MAX_ELEMENT];
    bool columnHasChess[MAX_ELEMENT];
    bool addDialogHasChess[MAX_ELEMENT];  
    bool subDialogHasChess[MAX_ELEMENT];
    
    int gN; //行数
    int gSolCount;
    void PrintSolution()
    {
    	for (int i = 0;i < gN;i++)
    	{
    		cout << solution[i] << " ";
    	}
    	cout << endl;
    }
    //check 皇后是否能放在[row,col]
    bool check(int row,int col)
    {
    	if (columnHasChess[col])
    	{
    		return false;
    	}
    	if (addDialogHasChess[row + col])
    	{
    		return false;
    	}
    	if (subDialogHasChess[row - col + gN])
    	{
    		return false;
    	}
    	return true;
    }
    void Go(int row)
    {
    	if (row == gN)
    	{
    		gSolCount ++;
    		PrintSolution();
    		return;
    	}
    	//第row行选择那一列呢
    	for (int i = 0;i < gN;i++)
    	{
    		if (check(row,i))
    		{
    			columnHasChess[i] = true;
    			addDialogHasChess[i + row] = true;
    			subDialogHasChess[row - i + gN] = true;
    			solution[row] = i;
    			Go(row + 1);
    			columnHasChess[i] = false;
    			addDialogHasChess[i + row] = false;
    			subDialogHasChess[row - i + gN] = false;
    		}
    	}
    }
    int _tmain(int argc, _TCHAR* argv[])
    {
    
    	gN = 8;
    	gSolCount = 0;
    	memset(columnHasChess,0,sizeof(columnHasChess));
    	memset(addDialogHasChess,0,sizeof(addDialogHasChess));
    	memset(subDialogHasChess,0,sizeof(subDialogHasChess));
    	Go(0);
    	cout << gSolCount << endl;
    }
    
  • 相关阅读:
    BZOJ 1630/2023 Ant Counting 数蚂蚁
    BZOJ 3997 组合数学
    BZOJ 2200 道路与航线
    BZOJ 3181 BROJ
    BZOJ 4011 落忆枫音
    BZOJ 4027 兔子与樱花
    vijos 1741 观光公交
    vijos 1776 关押罪犯
    vijos 1780 开车旅行
    5、异步通知机制
  • 原文地址:https://www.cnblogs.com/speedmancs/p/2072773.html
Copyright © 2011-2022 走看看