search
Homephp教程PHP源码php解八皇后以及多皇后问题。

[PHP]代码  

<?php
function f($q, $f = false) { /* $f 是标记,如果为 false 将重新初始化 */
	static $c = 0; /* 计数器, 解个数 */
	static $l = array(); /* 当前皇后存在的列, 键名记录行 */
	static $n = 0; /* 当前皇后,从0计数,表示第一个 */ 

	/* BUG FIX 增设初始化内容,感谢 @曹林剑 发现此BUG */
	if(!$f) {
		$c = 0;
		$l = array();
		$n=0;
	}

	/* 尝试放入皇后 */
	for($l[$n] = 0; $l[$n] < $q; $l[$n]++) {
		/* 验证皇后是否可以放入*/
		for($i = 0; $i < $n;$i++) {
			/* 验证是否可放入,冲突直接跳出本次筛选 */
			if(($l[$i] == $l[$n] || $l[$i] - $l[$n] == $i - $n || $l[$i] - $l[$n] == $n - $i )) continue 2;
		}
		/* 验证通过,可以放置本次 */

		/* 如果没有达到最后一个 */
		if($n < ($q - 1)) {
			$n++; /* 下一个皇后 */
			f($q, true); /* 第2个参数表示不会破坏内部存放数值*/
			$n--; /* 本层还有其他位置要验证, 还原后继续验证本层 */
		}
		/* 达到最后一个, 计数器+1 */
		else {
			$c++;
		}
	}
	return $c;
}

/* f(8); 可以返回 8 皇后解个数, 要想知道所有解, 可 在  "达到最后一个,计算器+1" 部分获取解详情。 */

                   

                   

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),