1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
| const readline = require('readline');
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
process.stdin.setEncoding('utf-8'); process.stdout.setEncoding('utf-8');
function question(prompt) { return new Promise((resolve) => { rl.question(prompt, (answer) => { resolve(answer); }); }); }
async function keyInYNStrict(prompt) { while (true) { const answer = await question(prompt); const normalized = answer.toLowerCase().trim(); if (normalized === 'y' || normalized === 'yes') return true; if (normalized === 'n' || normalized === 'no') return false; console.log('请输入 y/n'); } }
const LANG = 'zh'; const TEXT = { zh: { title: '八数码问题求解程序', initialStatePrompt: '[初始状态输入]', targetStatePrompt: '[目标状态输入]', inputMethod: '请选择输入方式:', inputMethod1: '1) 完整输入(含0)', inputMethod2: '2) 指定数字+空白位置', selectOption: '选项:', inputFullState: '请输入完整状态(含0,空格分隔):', inputNumbersPrompt: '请输入1-9的数字序列(空格分隔):', inputBlankIndex: '请输入空白位置索引(0-8):', solving: '正在求解中...', solutionFound: '✅ 找到最优解(%s步)', timeUsed: '🕒 耗时:%s秒', statesExplored: '🔍 探索状态数:%s', pathPreview: '🗺️ 路径预览:', stepFormat: 'Step %d (%s):', directionMap: { up: '↑', down: '↓', left: '←', right: '→' }, noSolution: '❌ 无解:', inversionMismatch: '初始与目标状态的逆序数奇偶性不一致', inversionInfo: 'ℹ️ 初始逆序数:%s(%s) 目标逆序数:%s(%s)', oddEven: { odd: '奇', even: '偶' }, invalidFormat: '格式错误:', duplicateDigits: '输入包含重复数字', missingDigits: '输入缺少必要数字', invalidBlank: '空白位置索引无效', outOfRange: '第%d个数字应为1-8,实际输入为%s', continuePrompt: '按Enter键继续...', searchTimeout: '搜索超时,是否继续?(y/n):', maxStepsReached: '已达到最大搜索深度(%s步),复杂度较高', } };
function t(key, ...args) { const text = TEXT[LANG][key]; if (typeof text === 'string' && args.length > 0) { return text.replace(/%s/g, () => args.shift()); } return text; }
function printBoard(state) { for (let i = 0; i < 3; i++) { console.log(state.slice(i * 3, i * 3 + 3).join(' ')); } }
function printStep(step, direction, prevState, nextState) { console.log(t('stepFormat', step, t('directionMap')[direction])); for (let i = 0; i < 3; i++) { const left = prevState.slice(i * 3, i * 3 + 3).join(' '); const right = nextState.slice(i * 3, i * 3 + 3).join(' '); const separator = i === 1 ? ' → ' : ' '; console.log(`${left}${separator}${right}`); } console.log(''); }
function getInversionCount(state) { const arr = state.filter(x => x !== 0); let count = 0; for (let i = 0; i < arr.length; i++) { for (let j = i + 1; j < arr.length; j++) { if (arr[i] > arr[j]) { count++; } } } return count; }
function isSolvable(initialState, targetState) { const initialInversion = getInversionCount(initialState); const targetInversion = getInversionCount(targetState); return initialInversion % 2 === targetInversion % 2; }
function validateState(state, isFullInput = true) { if (state.length !== 9) { return { valid: false, error: t('invalidFormat') }; } const digits = new Set(); for (let i = 0; i < state.length; i++) { if (isFullInput && (state[i] < 0 || state[i] > 8)) { return { valid: false, error: t('outOfRange', i + 1, state[i]) }; } else if (!isFullInput && (state[i] < 1 || state[i] > 9)) { return { valid: false, error: t('outOfRange', i + 1, state[i]) }; } if (digits.has(state[i])) { return { valid: false, error: t('duplicateDigits') }; } digits.add(state[i]); } if (isFullInput && !digits.has(0)) { return { valid: false, error: t('missingDigits') }; } return { valid: true }; }
function manhattanDistance(state, goal) { let distance = 0; for (let i = 0; i < state.length; i++) { const value = state[i]; if (value !== 0) { const currentPos = { x: i % 3, y: Math.floor(i / 3) }; const goalIndex = goal.indexOf(value); const goalPos = { x: goalIndex % 3, y: Math.floor(goalIndex / 3) }; distance += Math.abs(currentPos.x - goalPos.x) + Math.abs(currentPos.y - goalPos.y); } } return distance; }
function getPossibleMoves(state) { const blankIndex = state.indexOf(0); const x = blankIndex % 3; const y = Math.floor(blankIndex / 3); const moves = []; if (y > 0) moves.push('up'); if (y < 2) moves.push('down'); if (x > 0) moves.push('left'); if (x < 2) moves.push('right'); return moves; }
function applyMove(state, move) { const newState = [...state]; const blankIndex = state.indexOf(0); const x = blankIndex % 3; const y = Math.floor(blankIndex / 3); let newBlankIndex; switch (move) { case 'up': newBlankIndex = blankIndex - 3; break; case 'down': newBlankIndex = blankIndex + 3; break; case 'left': newBlankIndex = blankIndex - 1; break; case 'right': newBlankIndex = blankIndex + 1; break; } newState[blankIndex] = newState[newBlankIndex]; newState[newBlankIndex] = 0; return newState; }
function getStateHash(state) { return state.join(''); }
function idaStar(initialState, goalState) { const startTime = Date.now(); let statesExplored = 0; let path = []; let bound = manhattanDistance(initialState, goalState); const maxDepth = 100; let shouldContinue = true; function search(state, g, bound, path, visited) { statesExplored++; if (!shouldContinue) { return { result: 'timeout', path, statesExplored }; } if (statesExplored % 10000 === 0 && (Date.now() - startTime) > 5000) { console.log(t('maxStepsReached', path.length)); shouldContinue = false; return { result: 'need_input', path, statesExplored }; } const f = g + manhattanDistance(state, goalState); if (f > bound) { return { result: 'bound', newBound: f }; } if (JSON.stringify(state) === JSON.stringify(goalState)) { return { result: 'found', path, statesExplored }; } if (g >= maxDepth) { return { result: 'depth_limit' }; } const stateHash = getStateHash(state); visited.add(stateHash); let min = Infinity; const moves = getPossibleMoves(state); for (const move of moves) { const nextState = applyMove(state, move); const nextStateHash = getStateHash(nextState); if (visited.has(nextStateHash)) continue; path.push({ state: [...state], move, nextState: [...nextState] }); const result = search(nextState, g + 1, bound, path, new Set(visited)); if (result.result === 'found' || result.result === 'timeout' || result.result === 'need_input') { return result; } if (result.result === 'bound') { min = Math.min(min, result.newBound); } path.pop(); } return { result: 'bound', newBound: min }; } return { async solve() { while (true) { path = []; shouldContinue = true; const result = search(initialState, 0, bound, path, new Set()); if (result.result === 'found') { return { ...result, timeUsed: (Date.now() - startTime) / 1000 }; } if (result.result === 'need_input') { const continueSearch = await keyInYNStrict(t('searchTimeout')); if (!continueSearch) { return { result: 'timeout', path: result.path, statesExplored: result.statesExplored, timeUsed: (Date.now() - startTime) / 1000 }; } continue; } if (result.result === 'timeout') { return { ...result, timeUsed: (Date.now() - startTime) / 1000 }; } if (result.result === 'depth_limit') { return { result: 'depth_limit', timeUsed: (Date.now() - startTime) / 1000 }; } if (result.newBound === Infinity) { return { result: 'no_solution', timeUsed: (Date.now() - startTime) / 1000 }; } bound = result.newBound; } } }; }
async function main() { console.clear(); console.log(`\n===== ${t('title')} =====\n`); console.log(t('initialStatePrompt')); console.log(t('inputMethod')); console.log(t('inputMethod1')); console.log(t('inputMethod2')); const initialInputOption = await question(t('selectOption')); let initialState; if (initialInputOption === '1') { const input = await question(t('inputFullState')); initialState = input.trim().split(/\s+/).map(Number); const validation = validateState(initialState); if (!validation.valid) { console.log(validation.error); await question(t('continuePrompt')); rl.close(); return; } } else if (initialInputOption === '2') { const input = await question(t('inputNumbersPrompt')); const numbers = input.trim().split(/\s+/).map(Number); if (numbers.length !== 9) { console.log(t('invalidFormat')); await question(t('continuePrompt')); rl.close(); return; } const validation = validateState(numbers, false); if (!validation.valid) { console.log(validation.error); await question(t('continuePrompt')); rl.close(); return; } const blankIndexStr = await question(t('inputBlankIndex')); const blankIndex = parseInt(blankIndexStr); if (isNaN(blankIndex) || blankIndex < 0 || blankIndex > 8) { console.log(t('invalidBlank')); await question(t('continuePrompt')); rl.close(); return; } initialState = [...numbers]; initialState[blankIndex] = 0; } else { console.log(t('invalidFormat')); await question(t('continuePrompt')); rl.close(); return; } console.log('\n初始状态:'); printBoard(initialState); console.log(''); console.log(t('targetStatePrompt')); console.log(t('inputMethod')); console.log(t('inputMethod1')); console.log(t('inputMethod2')); const targetInputOption = await question(t('selectOption')); let targetState; if (targetInputOption === '1') { const input = await question(t('inputFullState')); targetState = input.trim().split(/\s+/).map(Number); const validation = validateState(targetState); if (!validation.valid) { console.log(validation.error); await question(t('continuePrompt')); rl.close(); return; } } else if (targetInputOption === '2') { const input = await question(t('inputNumbersPrompt')); const numbers = input.trim().split(/\s+/).map(Number); if (numbers.length !== 9) { console.log(t('invalidFormat')); await question(t('continuePrompt')); rl.close(); return; } const validation = validateState(numbers, false); if (!validation.valid) { console.log(validation.error); await question(t('continuePrompt')); rl.close(); return; } const blankIndexStr = await question(t('inputBlankIndex')); const blankIndex = parseInt(blankIndexStr); if (isNaN(blankIndex) || blankIndex < 0 || blankIndex > 8) { console.log(t('invalidBlank')); await question(t('continuePrompt')); rl.close(); return; } targetState = [...numbers]; targetState[blankIndex] = 0; } else { console.log(t('invalidFormat')); await question(t('continuePrompt')); rl.close(); return; } console.log('\n目标状态:'); printBoard(targetState); console.log(''); if (!isSolvable(initialState, targetState)) { console.log(t('noSolution'), t('inversionMismatch')); const initialInversion = getInversionCount(initialState); const targetInversion = getInversionCount(targetState); console.log( t( 'inversionInfo', initialInversion, t('oddEven')[initialInversion % 2 ? 'odd' : 'even'], targetInversion, t('oddEven')[targetInversion % 2 ? 'odd' : 'even'] ) ); await question(t('continuePrompt')); rl.close(); return; } console.log(t('solving')); console.log(initialState); const solver = idaStar(initialState, targetState); const solution = await solver.solve(); if (solution.result === 'found') { console.log(t('solutionFound', solution.path.length)); console.log(t('timeUsed', solution.timeUsed.toFixed(2))); console.log(t('statesExplored', solution.statesExplored)); console.log(t('pathPreview')); console.log('Initial:'); printBoard(initialState); console.log(''); for (let i = 0; i < solution.path.length; i++) { const step = solution.path[i]; printStep(i + 1, step.move, step.state, step.nextState); } } else if (solution.result === 'no_solution') { console.log(t('noSolution')); } else if (solution.result === 'timeout') { console.log(t('maxStepsReached', solution.path.length)); } await question(t('continuePrompt')); rl.close(); }
main().catch(err => { console.error('程序发生错误:', err); rl.close(); });
|