HarmonyOS数独候选台连载13:有界搜索与多解识别【共创稿事节】
HarmonyOS数独候选台连载05:有界搜索与多解识别【共创稿事节】
单格唯一候选可以解释局部填写,但有些题面会停在多个候选并存的状态。此时若直接把搜索找到的第一份完整答案称为唯一解,就会漏掉其他合法分支。数独候选台在既有候选服务之外增加带节点预算的深度搜索,最多收集两份解,并把搜索完成与预算截断作为不同的结论条件。

分析题面与编辑题面分开
搜索入口接收八十一格数字数组,先检查长度、数字范围与行列宫冲突,然后复制数组。递归只修改这份工作副本,当前PuzzleHistory、固定格标记和编辑步骤均保持原值。用户点击分析当前题面,只产生报告,不自动填写任何格。
当前页面仍使用同一份初始题目与history.state。查询候选、应用唯一提示、手动填写以及撤销重做继续保留。分析服务接受一般合法数字数组,便于分别检查完整题面、缺少部分数字的题面和空题面,而页面编辑权限仍由原固定格规则控制。
下面五个文件完整保留题面、候选、编辑事务、单步提示和历史服务,放入entry/src/main/ets对应目录。新增搜索复用候选查询,不在递归内部重新维护另一套行列宫位运算表,避免两种计算方式在空格或宫边界上产生分歧。
// model/Puzzle.ets
export function initialPuzzle(): number[] {
const rows: string[] = ['530070000','600195000','098000060',
'800060003','400803001','700020006','060000280','000419005','000080079'];
const board: number[] = [];
for (const row of rows) for (let col: number = 0; col<9; col++) board.push(Number(row[col]));
return board;
}
export function requireBoard(board: number[]): void {
if (board.length!==81) throw new Error('题面需为81格');
for (const value of board) if (!Number.isInteger(value) || value<0 || value>9)
throw new Error('题面格值需为0至9');
}
export function parseCell(rowText: string,colText: string): number {
const row: string = rowText.trim(); const col: string = colText.trim();
if (!/^[1-9]$/.test(row) || !/^[1-9]$/.test(col)) throw new Error('行列需为1至9');
return (Number(row)-1)*9+Number(col)-1;
}
// service/Candidates.ets
import { requireBoard } from '../model/Puzzle';
export interface CandidateInfo { rowUsed: number[]; colUsed: number[]; boxUsed: number[]; values: number[]; }
function uniqueDigits(values: number[]): number[] {
const result: number[] = [];
for (let value: number = 1; value<=9; value++) if (values.indexOf(value)>=0) result.push(value);
return result;
}
export function queryCandidates(board: number[],index: number): CandidateInfo {
requireBoard(board);
if (!Number.isInteger(index) || index<0 || index>=81) throw new Error('目标格超出范围');
if (board[index]!==0) throw new Error('目标格已有数字');
const row: number = Math.floor(index/9); const col: number = index%9;
const rowValues: number[] = []; const colValues: number[] = []; const boxValues: number[] = [];
for (let offset: number = 0; offset<9; offset++) {
rowValues.push(board[row*9+offset]); colValues.push(board[offset*9+col]);
}
const top: number = Math.floor(row/3)*3; const left: number = Math.floor(col/3)*3;
for (let dr: number = 0; dr<3; dr++) for (let dc: number = 0; dc<3; dc++)
boxValues.push(board[(top+dr)*9+left+dc]);
const rowUsed: number[] = uniqueDigits(rowValues);
const colUsed: number[] = uniqueDigits(colValues);
const boxUsed: number[] = uniqueDigits(boxValues);
const used: boolean[] = [false,false,false,false,false,false,false,false,false,false];
for (const value of rowUsed.concat(colUsed,boxUsed)) used[value]=true;
const result: number[] = [];
for (let value: number = 1; value<=9; value++) {
if (!used[value]) result.push(value);
}
return {rowUsed,colUsed,boxUsed,values:result};
}
export function digitsText(values: number[]): string { return values.length===0 ? '无' : values.join('、'); }
// service/PuzzleEdit.ets
import { initialPuzzle, requireBoard } from '../model/Puzzle';
export interface PuzzleState { board: number[]; givens: boolean[]; }
export type UnitKind = 'row' | 'col' | 'box';
export interface Conflict { kind: UnitKind; unit: number; digit: number; indices: number[]; }
export function createPuzzleState(): PuzzleState {
const board: number[] = initialPuzzle();
return {board,givens:board.map((value: number) => value!==0)};
}
export function requirePuzzleState(state: PuzzleState): void {
requireBoard(state.board);
if (state.givens.length!==81) throw new Error('固定格标记长度错误');
const seed: number[] = initialPuzzle();
for (let i: number = 0; i<81; i++) {
if (state.givens[i] !== (seed[i]!==0) || (seed[i]!==0 && state.board[i]!==seed[i]))
throw new Error('固定题面不一致');
}
}
export function unitIndices(kind: UnitKind,unit: number): number[] {
if (!Number.isInteger(unit) || unit<0 || unit>=9) throw new Error('区域位置错误');
if (kind!=='row' && kind!=='col' && kind!=='box') throw new Error('区域类型错误');
const result: number[] = [];
for (let offset: number = 0; offset<9; offset++) {
if (kind==='row') result.push(unit*9+offset);
else if (kind==='col') result.push(offset*9+unit);
else result.push((Math.floor(unit/3)*3+Math.floor(offset/3))*9+(unit%3)*3+offset%3);
}
return result;
}
export function findConflicts(board: number[]): Conflict[] {
requireBoard(board);
const result: Conflict[] = [];
const kinds: UnitKind[] = ['row','col','box'];
for (const kind of kinds) for (let unit: number = 0; unit<9; unit++) {
const points: number[] = unitIndices(kind,unit);
for (let digit: number = 1; digit<=9; digit++) {
const matches: number[] = points.filter((index: number) => board[index]===digit);
if (matches.length>1) result.push({kind,unit,digit,indices:matches});
}
}
return result;
}
export function conflictText(conflict: Conflict): string {
const name: string = conflict.kind==='row' ? '行' : conflict.kind==='col' ? '列' : '宫';
return `第${conflict.unit+1}${name}数字${conflict.digit}重复`;
}
export function parseDigit(text: string): number {
const value: string = text.trim();
if (!/^[0-9]$/.test(value)) throw new Error('填入值需为0至9,0表示清空');
return Number(value);
}
export function commitEdit(state: PuzzleState,index: number,value: number): PuzzleState {
requirePuzzleState(state);
if (!Number.isInteger(index) || index<0 || index>=81) throw new Error('目标格超出范围');
if (!Number.isInteger(value) || value<0 || value>9) throw new Error('填入值超出范围');
if (state.givens[index]) throw new Error('固定题面格不可修改');
if (findConflicts(state.board).length>0) throw new Error('当前题面存在冲突');
const next: number[] = state.board.slice(); next[index]=value;
const conflicts: Conflict[] = findConflicts(next);
if (conflicts.length>0) throw new Error(conflictText(conflicts[0]));
return {board:next,givens:state.givens.slice()};
}
// service/SingleHint.ets
import { CandidateInfo, queryCandidates } from './Candidates';
import { PuzzleState, requirePuzzleState, findConflicts, commitEdit } from './PuzzleEdit';
export interface SingleHint { index: number; value: number; boardKey: string; info: CandidateInfo; }
export function findSingleHints(state: PuzzleState): SingleHint[] {
requirePuzzleState(state);
if (findConflicts(state.board).length>0) throw new Error('当前题面存在冲突');
const result: SingleHint[] = [];
const boardKey: string = state.board.join('');
for (let index: number = 0; index<81; index++) {
if (state.board[index]!==0) continue;
const info: CandidateInfo = queryCandidates(state.board,index);
if (info.values.length===1) {
result.push({index,value:info.values[0],boardKey,info});
}
}
return result;
}
export function applySingleHint(state: PuzzleState,hint: SingleHint): PuzzleState {
requirePuzzleState(state);
if (state.board.join('')!==hint.boardKey) throw new Error('题面已变化,请刷新提示');
const current: CandidateInfo = queryCandidates(state.board,hint.index);
if (current.values.length!==1 || current.values[0]!==hint.value)
throw new Error('当前格不满足单格唯一候选');
return commitEdit(state,hint.index,hint.value);
}
export function hintText(hint: SingleHint): string {
return `${Math.floor(hint.index/9)+1}行${hint.index%9+1}列填${hint.value}`;
}
// service/History.ets
import { PuzzleState, createPuzzleState, commitEdit } from './PuzzleEdit';
export interface EditStep { index: number; before: number; after: number; group: string; }
export interface PuzzleHistory { state: PuzzleState; steps: EditStep[]; cursor: number; }
export function createHistory(): PuzzleHistory { return {state:createPuzzleState(),steps:[],cursor:0}; }
function copyStep(step: EditStep): EditStep {
return {index:step.index,before:step.before,after:step.after,group:step.group};
}
export function recordEdit(history: PuzzleHistory,index: number,value: number,group: string): PuzzleHistory {
const next: PuzzleState = commitEdit(history.state,index,value);
const before: number = history.state.board[index];
if (before===value) return history;
const steps: EditStep[] = history.steps.slice(0,history.cursor).map(copyStep);
const last: EditStep | undefined = steps.length>0 ? steps[steps.length-1] : undefined;
const atEnd: boolean = history.cursor===history.steps.length;
if (atEnd && group.length>0 && last!==undefined && last.index===index && last.group===group && last.after===before) {
if (last.before===value) steps.pop();
else steps[steps.length-1]={index,before:last.before,after:value,group};
} else steps.push({index,before,after:value,group});
return {state:next,steps,cursor:steps.length};
}
export function undo(history: PuzzleHistory): PuzzleHistory {
if (history.cursor===0) throw new Error('没有可撤销步骤');
const step: EditStep = history.steps[history.cursor-1];
if (history.state.board[step.index]!==step.after) throw new Error('历史与题面不一致');
return {state:commitEdit(history.state,step.index,step.before),steps:history.steps.map(copyStep),cursor:history.cursor-1};
}
export function redo(history: PuzzleHistory): PuzzleHistory {
if (history.cursor===history.steps.length) throw new Error('没有可重做步骤');
const step: EditStep = history.steps[history.cursor];
if (history.state.board[step.index]!==step.before) throw new Error('历史与题面不一致');
return {state:commitEdit(history.state,step.index,step.after),steps:history.steps.map(copyStep),cursor:history.cursor+1};
}
选择候选最少的空格展开
每进入一个搜索节点,扫描当前工作题面的空格,取候选数量最少的一格作为分支点。候选相同时保留扫描中较早的位置,候选数字则沿用服务的升序输出。这个确定顺序便于比较不同预算下的报告,也便于复查递归路径。
如果某个空格候选为空,当前分支立即结束;如果没有空格,当前工作题面是一份完整解,解数量增加一,并在第一次发现时复制整个题面保存。候选数量少的格优先展开,可以减少无关分支,但最终结论仍取决于完整搜索或发现第二份解。
每个候选值写入目标格后进入子节点,子节点返回就把目标恢复为零。即使已经达到两解或预算耗尽,也先完成这一层的恢复,再逐层返回。恢复动作使其他分支共享工作数组时不会读到上一条分支遗留的数字。
// service/Search.ets
import { requireBoard } from '../model/Puzzle';
import { queryCandidates } from './Candidates';
import { findConflicts } from './PuzzleEdit';
export interface SearchReport { status: string; solutions: number; nodes: number; cutoff: boolean; first: number[]; boardKey: string; }
export function idleReport(): SearchReport {
return {status:'待分析',solutions:0,nodes:0,cutoff:false,first:[],boardKey:''};
}
export function parseBudget(text: string): number {
const value: string = text.trim();
if (!/^[1-9][0-9]{0,4}$/.test(value) || Number(value)>10000) throw new Error('节点预算需为1至10000');
return Number(value);
}
export function analyzePuzzle(source: number[],budget: number): SearchReport {
requireBoard(source);
if (findConflicts(source).length>0) throw new Error('当前题面存在冲突');
if (!Number.isInteger(budget) || budget<1 || budget>10000) throw new Error('节点预算超出范围');
const board: number[] = source.slice();
const report: SearchReport = idleReport(); report.boardKey=source.join('');
function visit(): void {
if (report.solutions>=2 || report.cutoff) return;
if (report.nodes>=budget) { report.cutoff=true; return; }
report.nodes++;
let target: number = -1; let values: number[] = [];
for (let i: number = 0; i<81; i++) {
if (board[i]!==0) continue;
const options: number[] = queryCandidates(board,i).values;
if (options.length===0) return;
if (target<0 || options.length<values.length) { target=i; values=options; }
}
if (target<0) {
report.solutions++;
if (report.solutions===1) report.first=board.slice();
return;
}
for (const value of values) {
board[target]=value; visit(); board[target]=0;
if (report.solutions>=2 || report.cutoff) return;
}
}
visit();
report.status=report.solutions>=2 ? '至少两解' : report.cutoff ? '尚未判定' : report.solutions===1 ? '唯一解' : '无解';
return report;
}
四种结论由搜索证据决定
找到第二份解就可以报告至少两解,不需要继续枚举所有答案。只找到一份且所有相关分支都已经结束,才报告唯一解;没有找到解且搜索完整结束,报告无解。预算耗尽时,只要还没有两份解,就报告尚未判定,保留已经找到的解数量供观察。
节点预算在每次准备进入节点时检查。根节点也计数,实际进入节点才增加计数;达到预算以后,只有仍需要进入下一个节点时才设置截断标记。因此完整题面在预算为一时可以直接得到唯一解,而未填完的默认题面在预算为一时会留下尚未判定。
| 已找到解数 | 预算截断 | 结论 |
|---|---|---|
| 0 | 否 | 无解 |
| 1 | 否 | 唯一解 |
| 0或1 | 是 | 尚未判定 |
| 2 | 任意 | 至少两解 |
服务把解数上限固定为二,因此至少两解是分类结论,数值二不是题目的全部解数量。first只保存第一份解的独立数组,便于后续内容核对;本篇页面只展示报告摘要,避免让解数组与当前用户编辑混在一起。
报告关联题面内容
SearchReport保留生成报告时的题面内容标识。页面显示报告前,将它与当前棋盘数字连接结果比较;内容不同显示待分析。手动输入、提示填写或撤销重做后,旧报告不会继续套在另一份题面上,重新分析才能得到当前结论。
题面回退到完全相同的内容时,可以再次显示相应报告,因为搜索约束相同。预算输入是下一次分析的草稿,修改它不会触发搜索,也不修改历史步骤。报告中的节点数与截断标记来自上一次明确点击分析时的计算。
// pages/Index.ets
import { initialPuzzle, parseCell } from '../model/Puzzle';
import { CandidateInfo, queryCandidates, digitsText } from '../service/Candidates';
import { PuzzleState, createPuzzleState, commitEdit, findConflicts, parseDigit } from '../service/PuzzleEdit';
import { SingleHint, findSingleHints, applySingleHint, hintText } from '../service/SingleHint';
import { PuzzleHistory, createHistory, recordEdit, undo, redo } from '../service/History';
import { SearchReport, idleReport, analyzePuzzle, parseBudget } from '../service/Search';
@Entry
@Component
struct Index {
@State report: SearchReport = idleReport();
@State budgetText: string = '10000';
@State history: PuzzleHistory = createHistory();
@State hints: SingleHint[] = findSingleHints(createPuzzleState());
@State hintIndex: number = 40;
@State digitText: string = '1';
@State candidateText: string = '候选:1、2、4';
@State rowText: string = '1';
@State colText: string = '3';
@State selected: number = 2;
@State info: CandidateInfo = queryCandidates(initialPuzzle(),2);
@State status: string = '已更新';
@State areaWidth: number = 360;
private analyze(): void {
try {
const report: SearchReport = analyzePuzzle(this.history.state.board,parseBudget(this.budgetText));
this.report=report; this.status='分析完成';
} catch (error) { this.status=error instanceof Error ? error.message : '分析失败'; }
}
private query(): void {
try {
const index: number = parseCell(this.rowText,this.colText);
const next: CandidateInfo = queryCandidates(this.history.state.board,index);
this.selected=index; this.info=next; this.candidateText=`候选:${digitsText(next.values)}`; this.status='已查询';
} catch (error) { this.status=error instanceof Error ? error.message : '查询失败'; }
}
private submit(): void {
try {
const index: number = parseCell(this.rowText,this.colText);
const value: number = parseDigit(this.digitText);
const history: PuzzleHistory = recordEdit(this.history,index,value,`manual:${index}`);
const next: PuzzleState = history.state;
const hints: SingleHint[] = findSingleHints(next);
this.history=history; this.refreshHints(hints); this.selected=index;
if (value===0) {
this.info=queryCandidates(next.board,index);
this.candidateText=`候选:${digitsText(this.info.values)}`;
} else this.candidateText='目标格已填';
this.status=`已写入${Math.floor(index/9)+1}行${index%9+1}列`;
} catch (error) { this.status=error instanceof Error ? error.message : '提交失败'; }
}
private refreshHints(hints: SingleHint[]): void {
const retained: boolean = hints.some((hint: SingleHint) => hint.index===this.hintIndex);
this.hints=hints;
if (!retained) this.hintIndex=hints.length>0 ? hints[0].index : -1;
}
private applyHint(hint: SingleHint): void {
try {
const next: PuzzleState = applySingleHint(this.history.state,hint);
const hints: SingleHint[] = findSingleHints(next);
this.history=recordEdit(this.history,hint.index,hint.value,'hint'); this.refreshHints(hints); this.selected=hint.index;
this.candidateText='目标格已填'; this.status=`已应用${hintText(hint)}`;
} catch (error) { this.status=error instanceof Error ? error.message : '提示应用失败'; }
}
private travel(back: boolean): void {
try {
const next: PuzzleHistory = back ? undo(this.history) : redo(this.history);
const hints: SingleHint[] = findSingleHints(next.state);
const index: number = back ? this.history.steps[this.history.cursor-1].index : this.history.steps[this.history.cursor].index;
this.history=next; this.refreshHints(hints); this.selected=index;
if (next.state.board[index]===0) {
this.info=queryCandidates(next.state.board,index); this.candidateText=`候选:${digitsText(this.info.values)}`;
} else this.candidateText='目标格已填';
this.status=back ? '已撤销' : '已重做';
} catch (error) { this.status=error instanceof Error ? error.message : '历史操作失败'; }
}
private reset(): void {
this.history=createHistory(); this.refreshHints(findSingleHints(this.history.state)); this.selected=2;
this.rowText='1'; this.colText='3'; this.digitText='1';
this.info=queryCandidates(this.history.state.board,2); this.candidateText='候选:1、2、4'; this.status='已恢复题面';
}
@Builder
searchPanel(width: number) {
Column({space:12}) {
if (this.report.boardKey===this.history.state.board.join('')) {
Text(`分析结论:${this.report.status}`).fontSize(26)
Text(`已找到解数:${this.report.solutions}`)
Text(`搜索节点:${this.report.nodes}`)
Text(`预算截断:${this.report.cutoff ? '是' : '否'}`)
} else { Text('分析结论:待分析').fontSize(26) }
Text(`当前已填:${this.history.state.board.filter((v: number) => v!==0).length}`)
Text(`当前空格:${this.history.state.board.filter((v: number) => v===0).length}`)
Text(`已应用步骤:${this.history.cursor}`)
Text('搜索参数').fontSize(22)
TextInput({text:this.budgetText,placeholder:'节点预算1至10000'})
.onChange((v: string) => { this.budgetText=v; })
Button('分析当前题面').backgroundColor('#445F97').onClick(() => { this.analyze(); })
Text(this.status)
}.width(width).padding(16).backgroundColor('#FFFFFF').borderRadius(16)
}
@Builder
historyPanel(width: number) {
Column({space:12}) {
Text(`当前:${Math.floor(this.selected/9)+1}行${this.selected%9+1}列`).fontSize(22)
Text(`当前格值:${this.history.state.board[this.selected]}`)
Text(`已应用步骤:${this.history.cursor}`)
Text(`可撤销:${this.history.cursor} · 可重做:${this.history.steps.length-this.history.cursor}`)
if (this.history.cursor>0) {
Text(`最近步骤:${this.history.steps[this.history.cursor-1].before}→${this.history.steps[this.history.cursor-1].after}`)
}
Button('撤销').enabled(this.history.cursor>0).onClick(() => { this.travel(true); })
Button('重做').enabled(this.history.cursor<this.history.steps.length).onClick(() => { this.travel(false); })
Text(`已填格:${this.history.state.board.filter((v: number) => v!==0).length} · 空格:${this.history.state.board.filter((v: number) => v===0).length}`)
Text(`题面冲突:${findConflicts(this.history.state.board).length}组`)
}.width(width).padding(16).backgroundColor('#FFFFFF').borderRadius(16)
}
@Builder
hintDetail(hint: SingleHint) {
Column({space:12}) {
Text(`提示:${hintText(hint)}`).fontSize(22)
Text(`行已用:${digitsText(hint.info.rowUsed)}`)
Text(`列已用:${digitsText(hint.info.colUsed)}`)
Text(`宫已用:${digitsText(hint.info.boxUsed)}`)
Text(`剩余候选:${hint.value}`).fontSize(26).fontColor('#445F97')
Button('应用当前提示').backgroundColor('#445F97').onClick(() => { this.applyHint(hint); })
}.width('100%')
}
@Builder
hintPanel(width: number) {
Column({space:12}) {
Text('有界搜索与多解识别').fontSize(22)
Text(`单格唯一候选:${this.hints.length}处`)
Flex({direction:FlexDirection.Row,wrap:FlexWrap.Wrap}) {
ForEach(this.hints,(hint: SingleHint) => {
Button(hintText(hint)).fontSize(12).width((width-56)/3).margin(4)
.backgroundColor(hint.index===this.hintIndex ? '#445F97' : '#A8B8D7')
.onClick(() => { this.hintIndex=hint.index; })
},(hint: SingleHint) => `${hint.index}`)
}.width('100%')
ForEach(this.hints.filter((hint: SingleHint) => hint.index===this.hintIndex),(hint: SingleHint) => {
this.hintDetail(hint)
},(hint: SingleHint) => `${hint.boardKey}:${hint.index}`)
if (this.hints.length===0) { Text('当前没有单格唯一候选') }
Text(`已填格:${this.history.state.board.filter((value: number) => value!==0).length} · 空格:${this.history.state.board.filter((value: number) => value===0).length}`)
Text(`题面冲突:${findConflicts(this.history.state.board).length}组`)
}.width(width).padding(16).backgroundColor('#FFFFFF').borderRadius(16)
}
@Builder
inputPanel(width: number) {
Column({space:12}) {
Text('目标格输入').fontSize(22)
TextInput({text:this.rowText,placeholder:'行'})
.onChange((value: string) => { this.rowText=value; this.status='输入待查询'; })
TextInput({text:this.colText,placeholder:'列'})
.onChange((value: string) => { this.colText=value; this.status='输入待查询'; })
TextInput({text:this.digitText,placeholder:'填入0至9,0清空'})
.onChange((value: string) => { this.digitText=value; this.status='输入待提交'; })
Button('提交填数').backgroundColor('#445F97').onClick(() => { this.submit(); })
Button('查询候选').backgroundColor('#445F97').onClick(() => { this.query(); })
Text(this.status)
Text(`已填格:${this.history.state.board.filter((value: number) => value!==0).length}`)
Text(`空格:${this.history.state.board.filter((value: number) => value===0).length}`)
}.width(width).padding(16).backgroundColor('#FFFFFF').borderRadius(16)
}
@Builder
resultPanel(width: number) {
Column({space:14}) {
Text(`目标:${Math.floor(this.selected/9)+1}行${this.selected%9+1}列`).fontSize(22)
Text(`当前格值:${this.history.state.board[this.selected]}`)
Text(`题面冲突:${findConflicts(this.history.state.board).length}组`)
Text(`有效修改:${this.history.cursor}`)
if (this.history.state.board[this.selected]===0) {
Text(`行已用:${digitsText(this.info.rowUsed)}`)
Text(`列已用:${digitsText(this.info.colUsed)}`)
Text(`宫已用:${digitsText(this.info.boxUsed)}`)
}
Text(this.candidateText).fontSize(26).fontColor('#445F97')
Button('恢复题面').onClick(() => { this.reset(); })
}.width(width).padding(16).backgroundColor('#FFFFFF').borderRadius(16)
}
build() {
Scroll() {
Column({space:16}) {
Text('数独候选台').fontSize(26).fontWeight(FontWeight.Bold)
Text('有界搜索与多解识别')
if (this.areaWidth>=840) {
Row({space:16}) {
Column({space:16}) {
this.searchPanel((this.areaWidth-56)/2)
this.historyPanel((this.areaWidth-56)/2)
this.hintPanel((this.areaWidth-56)/2)
}
Column({space:16}) {
this.inputPanel((this.areaWidth-56)/2)
this.resultPanel((this.areaWidth-56)/2)
}
}.alignItems(VerticalAlign.Top)
} else {
this.searchPanel(this.areaWidth-40)
this.historyPanel(this.areaWidth-40)
this.hintPanel(this.areaWidth-40)
this.inputPanel(this.areaWidth-40)
this.resultPanel(this.areaWidth-40)
}
}.width('100%').padding(20)
}.width('100%').height('100%').backgroundColor('#F1F4FA')
.onAreaChange((oldArea: Area,newArea: Area) => {
const width: number = Number(newArea.width);
if (Number.isFinite(width) && width>40 && width!==this.areaWidth) this.areaWidth=width;
})
}
}

页面把搜索摘要放在历史区之前,保留当前已填格、空格和已应用步骤数,方便确认分析没有写入答案。窄屏纵向滚动,宽屏左侧放分析、历史与提示,右侧放输入与查询。窗口变化只重排组件,不重新执行搜索,也不清空用户步骤。
本篇节点预算限定为一至一万的正整数,解析拒绝零、小数和超范围值。节点预算限制的是搜索工作量,不是毫秒时间。每个节点都包含候选扫描,后续题目规模或交互要求提高时,可进一步把运算放到独立任务并增加取消控制,页面仍使用相同的报告分类。
用不同题面区分停止原因
默认初始题面有三十个已有数字。按照本篇固定的最少候选顺序,预算一万时搜索可以得到唯一解,节点计数为五十二;当前已填仍为三十、空格五十一、历史步骤为零。报告改变的是分析状态,页面事实保持不变。

将预算改为一再次分析,根节点可以被检查,但后续子节点受预算阻止,结论应为尚未判定。这个结果与无解不同,不能因为解数为零就提前结束分类。恢复较大预算后再分析,应按同一候选顺序继续得到完整搜索的结论。
多解样本可以从一份完整合法题面移除所有一和二,其余数字保持原位置。原解中的一、二对调以后仍满足基本约束,因此至少存在两种填写。服务应在发现第二份答案后停止,而不是要求列出全部解才允许报告多解。
检查副本恢复与报告独立性
可以在调用分析前保存输入数组,分别以充足预算和极小预算运行,然后逐格比较输入是否变化。检查first时也要确认它不是工作数组的引用,否则回溯清零会把已经找到的答案破坏。不同调用返回的报告与解数组应彼此独立。
遇到误报唯一解时,检查是否在找到第一份后直接返回整个搜索;遇到预算耗尽却显示无解时,检查最终状态选择是否优先处理cutoff;遇到答案中有空格时,检查完整节点判断和first复制时机。每种问题都对应清晰的控制流位置。
基本冲突检查与无解判定也要区分。已有数字重复时,输入在搜索前被拒绝;没有重复却无法完成的题面,需要搜索所有分支后才能报告无解。候选为空只结束当前分支,其他候选分支仍可能存在合法答案。
有界搜索至此形成独立的分析层:副本承载试填,候选服务决定分支,预算与两解上限控制停止,报告依据搜索是否完整分类。编辑历史继续记录用户接受的变化,下一章刷新候选缓存时,也能以同一份题面内容作为派生结果的关联依据。
节点数只在固定的扫描顺序和候选排序下具有可比较性。以后改变选格策略,同一题面的节点数可能变化,解分类仍应保持一致。对比两个实现时,应同时核对输入内容、预算、停止原因与答案合法性,而不能用更少节点直接代替正确性判断。预算输入失败时,当前题面和历史仍保持原值,报告也继续关联原来的题面内容。
相关资料
更多推荐




所有评论(0)