@@ -457,6 +457,58 @@ var solveNQueens = function(n) {
457457};
458458```
459459
460+ ## TypeScript
461+
462+ ``` typescript
463+ function solveNQueens(n : number ): string [][] {
464+ const board: string [][] = new Array (n ).fill (0 ).map (_ => new Array (n ).fill (' .' ));
465+ const resArr: string [][] = [];
466+ backTracking (n , 0 , board );
467+ return resArr ;
468+ function backTracking(n : number , rowNum : number , board : string [][]): void {
469+ if (rowNum === n ) {
470+ resArr .push (transformBoard (board ));
471+ return ;
472+ }
473+ for (let i = 0 ; i < n ; i ++ ) {
474+ if (isValid (i , rowNum , board ) === true ) {
475+ board [rowNum ][i ] = ' Q' ;
476+ backTracking (n , rowNum + 1 , board );
477+ board [rowNum ][i ] = ' .' ;
478+ }
479+ }
480+ }
481+ };
482+ function isValid(col : number , row : number , board : string [][]): boolean {
483+ const n: number = board .length ;
484+ if (col < 0 || col >= n || row < 0 || row >= n ) return false ;
485+ // 检查列
486+ for (let row of board ) {
487+ if (row [col ] === ' Q' ) return false ;
488+ }
489+ // 检查45度方向
490+ let x: number = col ,
491+ y: number = row ;
492+ while (y >= 0 && x < n ) {
493+ if (board [y -- ][x ++ ] === ' Q' ) return false ;
494+ }
495+ // 检查135度方向
496+ x = col ;
497+ y = row ;
498+ while (x >= 0 && y >= 0 ) {
499+ if (board [y -- ][x -- ] === ' Q' ) return false ;
500+ }
501+ return true ;
502+ }
503+ function transformBoard(board : string [][]): string [] {
504+ const resArr = [];
505+ for (let row of board ) {
506+ resArr .push (row .join (' ' ));
507+ }
508+ return resArr ;
509+ }
510+ ```
511+
460512### Swift
461513
462514``` swift
0 commit comments