【数据结构与算法】回溯算法

LeetCode

N皇后 问题  

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

上图为 8 皇后问题的一种解法。

给定一个整数 n,返回所有不同的 n 皇后问题的解决方案。

每一种解法包含一个明确的 n 皇后问题的棋子放置方案,该方案中 'Q' 和 '.' 分别代表了皇后和空位。

class Solution {
   int *result;
   vector<vector<string>> ans;
   int count;
public:
    vector<vector<string>> solveNQueens(int n) {
       
        result=new int[n];
        
        count=n;
        cal8queens(0,n);
        return ans;
    }
  
   void cal8queens(int row,int num) { // 调用方式:cal8queens(0);
        if (row == num) { 
           printQueens(result);
           return; // 8 行棋子都放好了,已经没法再往下递归了,所以就 return
        }
        for (int column = 0; column <count; ++column) { //递归中的for循环 是双杀
            if (isOk(row, column)) { // 有些放法不满足要求
              result[row] = column; // 第 row 行的棋子放到了 column 列
              cal8queens(row+1,num); // 考察下一行
            }
        }
    }

     bool isOk(int row, int column) {
      int leftup = column - 1, rightup = column + 1;
      for (int i = row-1; i >= 0; --i) { 
        if (result[i] == column) return false; 
        if (leftup >= 0) { 
          if (result[i] == leftup) return false;
        }
        if (rightup < count) { 
          if (result[i] == rightup) return false;
        }
        --leftup; ++rightup;
      }
      return true;
    }
     void printQueens(int result[]) { 
      vector<string> solution;
      for (int row = 0; row < count; ++row) {
        string rowstring;
        for (int column = 0; column < count; ++column) {
          if (result[row] == column) rowstring+="Q";
          else rowstring+=".";
        }
        solution.push_back(rowstring);            
      }
      
      ans.push_back(solution);
     
    }

};

  

猜你喜欢

转载自www.cnblogs.com/jiwen/p/11436761.html
今日推荐