回溯法解决8皇后问题

C
import rand

fn main(){
  mut board := [][]string{len: 8, init: []string{len: 8, init: '.'}}
  mut boards := [][][]string{}

  //backtrack
  backtrack(board, 0, mut boards)

  //result
  n := rand.intn(92)
  println('the number $n board')
  for row:=0; row<8; row++{
    println(boards[n][row])
  }
  println('total: $boards.len')
  println('cool...over')
}

fn backtrack(board [][]string, row int, mut boards [][][]string){
  mut b := board.clone()
  if row == 8 {
    boards << b
    return
  }
  for col:=0; col<8; col++{
    if !is_valid(b, row, col){
      continue
    }
    b[row][col] = 'Q'
    backtrack(b, row+1, mut boards)
    b[row][col] = '.'
  }
}

fn is_valid(board [][]string, row int, col int) bool{
  n := board.len
  for i:=0; i<row; i++{
    if board[i][col] == 'Q'{
      return false
    }
  }

  for i, j :=row-1, col+1;
        i>=0 && j<n; i--, j++ {
      if board[i][j] == 'Q'{
        return false
      }
  }

  for i, j :=row-1, col-1;
        i>=0 && j>=0; i--, j-- {
      if board[i][j] == 'Q'{
        return false
      }
  }

  return true

}

Hey! Want to join a camp talk like this, come sign up an account.