@@ -356,6 +356,84 @@ public class Solution {
356
356
}
357
357
```
358
358
359
+ ``` php
360
+ class Solution {
361
+ /**
362
+ * @param string[][] $board
363
+ * @return bool
364
+ */
365
+
366
+ public function solveSudoku(& $board) {
367
+ if (isSolved($board)) {
368
+ return true;
369
+ }
370
+
371
+ $emptyCell = findEmptyCell($board);
372
+ $row = $emptyCell[0];
373
+ $col = $emptyCell[1];
374
+
375
+ for ($num = 1; $num <= 9; $num++) {
376
+ if (isValid($board, $row, $col, $num)) {
377
+ $board[$row][$col] = (string) $num;
378
+ if ($this->solveSudoku($board)) {
379
+ return true;
380
+ }
381
+ $board[$row][$col] = '.';
382
+ }
383
+ }
384
+ return false;
385
+ }
386
+ }
387
+
388
+ function isSolved($board) {
389
+ foreach ($board as $row) {
390
+ if (in_array('.', $row)) {
391
+ return false;
392
+ }
393
+ }
394
+ return true;
395
+ }
396
+
397
+ function findEmptyCell($board) {
398
+ for ($row = 0; $row < 9; $row++) {
399
+ for ($col = 0; $col < 9; $col++) {
400
+ if ($board[$row][$col] === '.') {
401
+ return [$row, $col];
402
+ }
403
+ }
404
+ }
405
+
406
+ return null;
407
+ }
408
+
409
+ function isValid($board, $row, $col, $num) {
410
+ for ($i = 0; $i < 9; $i++) {
411
+ if ($board[$row][$i] == $num) {
412
+ return false;
413
+ }
414
+ }
415
+
416
+ for ($i = 0; $i < 9; $i++) {
417
+ if ($board[$i][$col] == $num) {
418
+ return false;
419
+ }
420
+ }
421
+
422
+ $startRow = floor($row / 3) * 3;
423
+ $endCol = floor($col / 3) * 3;
424
+
425
+ for ($i = 0; $i < 3; $i++) {
426
+ for ($j = 0; $j < 3; $j++) {
427
+ if ($board[$startRow + $i][$endCol + $j] == $num) {
428
+ return false;
429
+ }
430
+ }
431
+ }
432
+
433
+ return true;
434
+ }
435
+ ```
436
+
359
437
<!-- tabs: end -->
360
438
361
439
<!-- end -->
0 commit comments