回溯算法随笔

1. n 皇后问题 研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。

function solveNQueens(n){
    //创建棋盘
  let board = new Array(n)
  for(let i = 0; i < n; i++){
    board[i] = new Array(n).fill(".")
  }
  //存储 col 列出现过的集合
  let cols = new Set()
  //存储正对称出现的集合
  let diag1 = new Set()
  //存储负对称出现的集合
  let diag2 = new Set()
  //创建符合出现皇后可能的集合
  let res = []
  
  //判断皇后是否符合条件函数
  const helper = (row) =>{
    if(row == n ){
      const stringBoard = board.slice();
      for(let i = 0; i < n; i++){
        stringBoard[i] = stringBoard[i].join("")
      }
      res.push(stringBoard)
      return
    }
  }

  for(let col = 0 ; col < n ; col++){
  if(!cols.has(col) && !diag1.has(col) && !diag2.has(col){
      board[row][col] = 'Q'
      cols.add(col)
      diag1.add(row -col)
      diag2.add(row + col)
      helper(row + 1)
      
board[row][col] = '.'
      cols.delete(col)
      diag1.delete(row -col)
      diag2.delete(row + col)

    }
  
  }
  helper(0)
  return res
}

2. 机器人运动轨迹算法坐标相加合不能大于n坐标个数

function movingCount(threshold,rows,cols){
    let visited = []
  for(let i = 0; i < rows; i++){
    visited.push([])
    for(let j = 0; j < cols;j++){
      visited[i][j] = false
    }
  }

  return moveCount(threshold,rows,cols,0,0,visited)
}
function moveCount(threshold,rows,cols,row,col,visited){
  if(row < 0 || col < 0 || row == rows || col == cols || visited[row][col]){
    return 0
  }
  let count = 0,
    sum = 0,
    temp = row +""+col;
  for(let i = 0; i < temp.length; i ++){
    sum += temp.charAt(i)/1
  }
  if(sum > threshold)return 0
  visited[row][col] = true
  return count = 1 + moveCount(threshold,rows,cols,row+1,col,visited) +
          
moveCount(threshold,rows,cols,row,col+1,visited) +
          moveCount(threshold,rows,cols,row-1,col,visited) +
          moveCount(threshold,rows,cols,row,col-1,visited)
}

3. [1,2,3] 数组的组合顺序

function combination(arr){
  let res = []
  let dfs = (path) =>{
    if(path.length == arr.length){
      res.push([...path])
      return
    }
    for(let i = 0; i < arr.length; i ++){
      if(path.indexOf(arr[i]) !== -1){
        continue
      }
      path.push(arr[i])
      dfs(path)
      path.pop()
    }
  }
dfs([])
return [] }

 

 

 

posted @ 2021-07-16 18:55  心之所指,行之所至  阅读(47)  评论(0)    收藏  举报