@@ -144,7 +144,61 @@ var totalNQueens = function(n) {
144
144
};
145
145
```
146
146
147
+ TypeScript:
148
+
149
+ ``` typescript
150
+ // 0-该格为空,1-该格有皇后
151
+ type GridStatus = 0 | 1 ;
152
+ function totalNQueens(n : number ): number {
153
+ let resCount: number = 0 ;
154
+ const chess: GridStatus [][] = new Array (n ).fill (0 )
155
+ .map (_ => new Array (n ).fill (0 ));
156
+ backTracking (chess , n , 0 );
157
+ return resCount ;
158
+ function backTracking(chess : GridStatus [][], n : number , startRowIndex : number ): void {
159
+ if (startRowIndex === n ) {
160
+ resCount ++ ;
161
+ return ;
162
+ }
163
+ for (let j = 0 ; j < n ; j ++ ) {
164
+ if (checkValid (chess , startRowIndex , j , n ) === true ) {
165
+ chess [startRowIndex ][j ] = 1 ;
166
+ backTracking (chess , n , startRowIndex + 1 );
167
+ chess [startRowIndex ][j ] = 0 ;
168
+ }
169
+ }
170
+ }
171
+ };
172
+ function checkValid(chess : GridStatus [][], i : number , j : number , n : number ): boolean {
173
+ // 向上纵向检查
174
+ let tempI: number = i - 1 ,
175
+ tempJ: number = j ;
176
+ while (tempI >= 0 ) {
177
+ if (chess [tempI ][tempJ ] === 1 ) return false ;
178
+ tempI -- ;
179
+ }
180
+ // 斜向左上检查
181
+ tempI = i - 1 ;
182
+ tempJ = j - 1 ;
183
+ while (tempI >= 0 && tempJ >= 0 ) {
184
+ if (chess [tempI ][tempJ ] === 1 ) return false ;
185
+ tempI -- ;
186
+ tempJ -- ;
187
+ }
188
+ // 斜向右上检查
189
+ tempI = i - 1 ;
190
+ tempJ = j + 1 ;
191
+ while (tempI >= 0 && tempJ < n ) {
192
+ if (chess [tempI ][tempJ ] === 1 ) return false ;
193
+ tempI -- ;
194
+ tempJ ++ ;
195
+ }
196
+ return true ;
197
+ }
198
+ ```
199
+
147
200
C
201
+
148
202
``` c
149
203
// path[i]为在i行,path[i]列上存在皇后
150
204
int *path;
0 commit comments