Open bibin-jaimon opened 1 month ago
https://leetcode.com/problems/n-queens/description/
const isValid = (board, col, row) => {
// check horizontal
for (let i = 0; i < col; i++) {
if (board[row][i] == 'Q') { return false }
}
// check vertical - not required because we fill colm wise so in one col one q there
// check diagonal
// left upper
for (let r = row, c=col; r >=0 && c>=0; r--, c--) {
if (board[r][c] == 'Q') { return false }
}
// left lower
for (let r = row, c=col; c>=0 && r<board.length ; c--, r++) {
if (board[r][c] == 'Q') { return false }
}
return true
}
const helper = (col, n, board, res) => {
if (col === n) {
res.push(board.map(item => item.join('')))
return
}
for (let row=0; row < n; row++) {
// check if board is valid
if (isValid(board, col, row) == true) {
board[row][col] = 'Q'
helper(col+1, n, board, res)
board[row][col] = '.'
}
}
}
var solveNQueens = function(n) {
// create row or column
// create board
// call helper to get result
const row = Array(n).fill('.')
const board = []
const res = []
let q = n
while(q--) {
board.push([...row])
}
helper(0, n, board, res)
return res
};
https://leetcode.com/problems/sudoku-solver/description/
var solveSudoku = function(board) {
const isValid = (board, row, col, digit) => {
for (let i = 0; i < 9; i++) {
if (board[row][i] == digit.toString()) return false
if (board[i][col] == digit.toString()) return false
const currentRow = (3*parseInt(row/3)) + parseInt(i/3)
const currentCol = (3*parseInt(col/3)) + i%3
if (board[currentRow][currentCol] == digit.toString()) return false
}
return true
}
for (let i = 0; i < 9; i++) {
for (let j = 0; j < 9; j++) {
if (board[i][j] == '.') {
for (let digit = 1; digit <= 9; digit++) {
if (isValid(board, i, j, digit) == true) {
board[i][j] = digit.toString()
if (solveSudoku(board)) return true
board[i][j] = '.'
}
}
return false
}
}
}
return true
};
Use recursion visualizer: https://recursion.vercel.app/
https://leetcode.com/problems/n-th-tribonacci-number/
https://leetcode.com/problems/climbing-stairs/
https://leetcode.com/problems/min-cost-climbing-stairs/
https://leetcode.com/problems/subsets/
https://leetcode.com/problems/house-robber-ii/
https://leetcode.com/problems/generate-parentheses/
https://leetcode.com/problems/decode-ways/description/
https://leetcode.com/problems/letter-combinations-of-a-phone-number/
https://leetcode.com/problems/decode-string/