zoukankan      html  css  js  c++  java
  • Go实现八皇后

    八皇后都成梗了,实际上就是个递归还有对角线公式。

    func isNotUnderAttack(row, col, n int, rows, hills, dales []int) bool {
        res := rows[col] + hills[row - col + 2 * n] + dales[row + col]
        return res == 0
    }
    
    func backtrack(row, count, n int, rows, hills, dales []int) int {
        for col := 0; col < n; col++ {
            if isNotUnderAttack(row, col, n, rows, hills, dales) {
                rows[col] = 1
                hills[row - col + 2 * n] = 1
                dales[row + col] = 1
    
                if row+1 == n {
                    count++
                } else {
                    count = backtrack(row + 1, count, n, rows, hills, dales)
                }
                
                rows[col] = 0
                hills[row - col + 2 * n] = 0
                dales[row + col] = 0
            }
        }
        return count
    }
    
    func totalNQueens(n int) int {
        rows := make([]int, n)
        hills := make([]int, 4*n-1)
        dales := make([]int, 2*n-1)
        return backtrack(0, 0, n, rows, hills, dales)
    }

    的确没啥人用Go写

    一个没有高级趣味的人。 email:hushui502@gmail.com
  • 相关阅读:
    站立会议报告(7)
    团队博客(13)
    团队博客(12)
    意见评论
    团队博客(11)
    团队博客(10)
    团队博客(9)
    团队博客(8)
    站立会议报告(6)
    Java Callable
  • 原文地址:https://www.cnblogs.com/CherryTab/p/12416500.html
Copyright © 2011-2022 走看看