From b52a98f178d7052870afe43d49d96b19cfb06fbe Mon Sep 17 00:00:00 2001 From: Justin Tse Date: Sun, 14 May 2023 01:18:40 +0800 Subject: [PATCH] Add JavaScript and TypeScript code of permutations and n_queens (Chapter of Backtracking) (#494) * Add JavaScript and TypeScript code of permutations and n_queens (Chapter of Backtracking) * Update n_queens.js * Update permutations_i.js * Update permutations_ii.js * Update n_queens.ts * Update permutations_i.ts * Update permutations_ii.ts --------- Co-authored-by: Yudong Jin --- .../chapter_backtracking/n_queens.js | 55 ++++++++++++++++ .../chapter_backtracking/permutations_i.js | 42 ++++++++++++ .../chapter_backtracking/permutations_ii.js | 44 +++++++++++++ .../chapter_backtracking/n_queens.ts | 65 +++++++++++++++++++ .../chapter_backtracking/permutations_i.ts | 49 ++++++++++++++ .../chapter_backtracking/permutations_ii.ts | 51 +++++++++++++++ 6 files changed, 306 insertions(+) create mode 100644 codes/javascript/chapter_backtracking/n_queens.js create mode 100644 codes/javascript/chapter_backtracking/permutations_i.js create mode 100644 codes/javascript/chapter_backtracking/permutations_ii.js create mode 100644 codes/typescript/chapter_backtracking/n_queens.ts create mode 100644 codes/typescript/chapter_backtracking/permutations_i.ts create mode 100644 codes/typescript/chapter_backtracking/permutations_ii.ts diff --git a/codes/javascript/chapter_backtracking/n_queens.js b/codes/javascript/chapter_backtracking/n_queens.js new file mode 100644 index 000000000..d854d19b0 --- /dev/null +++ b/codes/javascript/chapter_backtracking/n_queens.js @@ -0,0 +1,55 @@ +/** + * File: n_queens.js + * Created Time: 2023-05-13 + * Author: Justin (xiefahit@gmail.com) + */ + +/* 回溯算法:N 皇后 */ +function backtrack(row, n, state, res, cols, diags1, diags2) { + // 当放置完所有行时,记录解 + if (row === n) { + res.push(state.map((row) => row.slice())); + return; + } + // 遍历所有列 + for (let col = 0; col < n; col++) { + // 计算该格子对应的主对角线和副对角线 + const diag1 = row - col + n - 1; + const diag2 = row + col; + // 剪枝:不允许该格子所在 (列 或 主对角线 或 副对角线) 包含皇后 + if (!(cols[col] || diags1[diag1] || diags2[diag2])) { + // 尝试:将皇后放置在该格子 + state[row][col] = 'Q'; + cols[col] = diags1[diag1] = diags2[diag2] = true; + // 放置下一行 + backtrack(row + 1, n, state, res, cols, diags1, diags2); + // 回退:将该格子恢复为空位 + state[row][col] = '#'; + cols[col] = diags1[diag1] = diags2[diag2] = false; + } + } +} + +/* 求解 N 皇后 */ +function nQueens(n) { + // 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位 + const state = Array.from({ length: n }, () => Array(n).fill('#')); + const cols = Array(n).fill(false); // 记录列是否有皇后 + const diags1 = Array(2 * n - 1).fill(false); // 记录主对角线是否有皇后 + const diags2 = Array(2 * n - 1).fill(false); // 记录副对角线是否有皇后 + const res = []; + + backtrack(0, n, state, res, cols, diags1, diags2); + return res; +} + +// Driver Code +const n = 4; +const res = nQueens(n); + +console.log(`输入棋盘长宽为 ${n}`); +console.log(`皇后放置方案共有 ${res.length} 种`); +res.forEach((state) => { + console.log('--------------------'); + state.forEach((row) => console.log(row)); +}); diff --git a/codes/javascript/chapter_backtracking/permutations_i.js b/codes/javascript/chapter_backtracking/permutations_i.js new file mode 100644 index 000000000..c0533eda3 --- /dev/null +++ b/codes/javascript/chapter_backtracking/permutations_i.js @@ -0,0 +1,42 @@ +/** + * File: permutations_i.js + * Created Time: 2023-05-13 + * Author: Justin (xiefahit@gmail.com) + */ + +/* 回溯算法:全排列 I */ +function backtrack(state, choices, selected, res) { + // 当状态长度等于元素数量时,记录解 + if (state.length === choices.length) { + res.push([...state]); + return; + } + // 遍历所有选择 + choices.forEach((choice, i) => { + // 剪枝:不允许重复选择元素 且 不允许重复选择相等元素 + if (!selected[i]) { + // 尝试:做出选择,更新状态 + selected[i] = true; + state.push(choice); + // 进行下一轮选择 + backtrack(state, choices, selected, res); + // 回退:撤销选择,恢复到之前的状态 + selected[i] = false; + state.pop(); + } + }); +} + +/* 全排列 I */ +function permutationsI(nums) { + const res = []; + backtrack([], nums, Array(nums.length).fill(false), res); + return res; +} + +// Driver Code +const nums = [1, 2, 3]; +const res = permutationsI(nums); + +console.log(`输入数组 nums = ${JSON.stringify(nums)}`); +console.log(`所有排列 res = ${JSON.stringify(res)}`); diff --git a/codes/javascript/chapter_backtracking/permutations_ii.js b/codes/javascript/chapter_backtracking/permutations_ii.js new file mode 100644 index 000000000..d0e27cec6 --- /dev/null +++ b/codes/javascript/chapter_backtracking/permutations_ii.js @@ -0,0 +1,44 @@ +/** + * File: permutations_ii.js + * Created Time: 2023-05-13 + * Author: Justin (xiefahit@gmail.com) + */ + +/* 回溯算法:全排列 II */ +function backtrack(state, choices, selected, res) { + // 当状态长度等于元素数量时,记录解 + if (state.length === choices.length) { + res.push([...state]); + return; + } + // 遍历所有选择 + const duplicated = new Set(); + choices.forEach((choice, i) => { + // 剪枝:不允许重复选择元素 且 不允许重复选择相等元素 + if (!selected[i] && !duplicated.has(choice)) { + // 尝试:做出选择,更新状态 + duplicated.add(choice); // 记录选择过的元素值 + selected[i] = true; + state.push(choice); + // 进行下一轮选择 + backtrack(state, choices, selected, res); + // 回退:撤销选择,恢复到之前的状态 + selected[i] = false; + state.pop(); + } + }); +} + +/* 全排列 II */ +function permutationsII(nums) { + const res = []; + backtrack([], nums, Array(nums.length).fill(false), res); + return res; +} + +// Driver Code +const nums = [1, 2, 2]; +const res = permutationsII(nums); + +console.log(`输入数组 nums = ${JSON.stringify(nums)}`); +console.log(`所有排列 res = ${JSON.stringify(res)}`); diff --git a/codes/typescript/chapter_backtracking/n_queens.ts b/codes/typescript/chapter_backtracking/n_queens.ts new file mode 100644 index 000000000..62e4cc0ef --- /dev/null +++ b/codes/typescript/chapter_backtracking/n_queens.ts @@ -0,0 +1,65 @@ +/** + * File: n_queens.ts + * Created Time: 2023-05-13 + * Author: Justin (xiefahit@gmail.com) + */ + +/* 回溯算法:N 皇后 */ +function backtrack( + row: number, + n: number, + state: string[][], + res: string[][][], + cols: boolean[], + diags1: boolean[], + diags2: boolean[] +): void { + // 当放置完所有行时,记录解 + if (row === n) { + res.push(state.map((row) => row.slice())); + return; + } + // 遍历所有列 + for (let col = 0; col < n; col++) { + // 计算该格子对应的主对角线和副对角线 + const diag1 = row - col + n - 1; + const diag2 = row + col; + // 剪枝:不允许该格子所在 (列 或 主对角线 或 副对角线) 包含皇后 + if (!(cols[col] || diags1[diag1] || diags2[diag2])) { + // 尝试:将皇后放置在该格子 + state[row][col] = 'Q'; + cols[col] = diags1[diag1] = diags2[diag2] = true; + // 放置下一行 + backtrack(row + 1, n, state, res, cols, diags1, diags2); + // 回退:将该格子恢复为空位 + state[row][col] = '#'; + cols[col] = diags1[diag1] = diags2[diag2] = false; + } + } +} + +/* 求解 N 皇后 */ +function nQueens(n: number): string[][][] { + // 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位 + const state = Array.from({ length: n }, () => Array(n).fill('#')); + const cols = Array(n).fill(false); // 记录列是否有皇后 + const diags1 = Array(2 * n - 1).fill(false); // 记录主对角线是否有皇后 + const diags2 = Array(2 * n - 1).fill(false); // 记录副对角线是否有皇后 + const res: string[][][] = []; + + backtrack(0, n, state, res, cols, diags1, diags2); + return res; +} + +// Driver Code +const n = 4; +const res = nQueens(n); + +console.log(`输入棋盘长宽为 ${n}`); +console.log(`皇后放置方案共有 ${res.length} 种`); +res.forEach((state) => { + console.log('--------------------'); + state.forEach((row) => console.log(row)); +}); + +export {}; diff --git a/codes/typescript/chapter_backtracking/permutations_i.ts b/codes/typescript/chapter_backtracking/permutations_i.ts new file mode 100644 index 000000000..17513a5a6 --- /dev/null +++ b/codes/typescript/chapter_backtracking/permutations_i.ts @@ -0,0 +1,49 @@ +/** + * File: permutations_i.ts + * Created Time: 2023-05-13 + * Author: Justin (xiefahit@gmail.com) + */ + +/* 回溯算法:全排列 I */ +function backtrack( + state: number[], + choices: number[], + selected: boolean[], + res: number[][] +): void { + // 当状态长度等于元素数量时,记录解 + if (state.length === choices.length) { + res.push([...state]); + return; + } + // 遍历所有选择 + choices.forEach((choice, i) => { + // 剪枝:不允许重复选择元素 且 不允许重复选择相等元素 + if (!selected[i]) { + // 尝试:做出选择,更新状态 + selected[i] = true; + state.push(choice); + // 进行下一轮选择 + backtrack(state, choices, selected, res); + // 回退:撤销选择,恢复到之前的状态 + selected[i] = false; + state.pop(); + } + }); +} + +/* 全排列 I */ +function permutationsI(nums: number[]): number[][] { + const res: number[][] = []; + backtrack([], nums, Array(nums.length).fill(false), res); + return res; +} + +// Driver Code +const nums: number[] = [1, 2, 3]; +const res: number[][] = permutationsI(nums); + +console.log(`输入数组 nums = ${JSON.stringify(nums)}`); +console.log(`所有排列 res = ${JSON.stringify(res)}`); + +export {}; diff --git a/codes/typescript/chapter_backtracking/permutations_ii.ts b/codes/typescript/chapter_backtracking/permutations_ii.ts new file mode 100644 index 000000000..782a45a6e --- /dev/null +++ b/codes/typescript/chapter_backtracking/permutations_ii.ts @@ -0,0 +1,51 @@ +/** + * File: permutations_ii.ts + * Created Time: 2023-05-13 + * Author: Justin (xiefahit@gmail.com) + */ + +/* 回溯算法:全排列 II */ +function backtrack( + state: number[], + choices: number[], + selected: boolean[], + res: number[][] +): void { + // 当状态长度等于元素数量时,记录解 + if (state.length === choices.length) { + res.push([...state]); + return; + } + // 遍历所有选择 + const duplicated = new Set(); + choices.forEach((choice, i) => { + // 剪枝:不允许重复选择元素 且 不允许重复选择相等元素 + if (!selected[i] && !duplicated.has(choice)) { + // 尝试:做出选择,更新状态 + duplicated.add(choice); // 记录选择过的元素值 + selected[i] = true; + state.push(choice); + // 进行下一轮选择 + backtrack(state, choices, selected, res); + // 回退:撤销选择,恢复到之前的状态 + selected[i] = false; + state.pop(); + } + }); +} + +/* 全排列 II */ +function permutationsII(nums: number[]): number[][] { + const res: number[][] = []; + backtrack([], nums, Array(nums.length).fill(false), res); + return res; +} + +// Driver Code +const nums: number[] = [1, 2, 2]; +const res: number[][] = permutationsII(nums); + +console.log(`输入数组 nums = ${JSON.stringify(nums)}`); +console.log(`所有排列 res = ${JSON.stringify(res)}`); + +export {};