Leetcode204: N-Queens II

来源:互联网 发布:这是我的战争 知乎 编辑:程序博客网 时间:2024/05/22 15:23

Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

有了上一题的解法,简单修改下即可

class Solution {private:    int num=0;public:      int isValid(int *a, int n, int row, int col)      {          int tmpcol=0;          for(int tmprow=0;tmprow<row;tmprow++)          {              tmpcol = a[tmprow];              if(tmpcol == col)// 同列                  return 0;              if((tmpcol-col) == (tmprow - row))// 在同一右斜线                  return 0;              if((tmpcol-col) == (row - tmprow))// 在同一左斜线                  return 0;          }          return 1;         }      void n_queens(int *a,int n, int index)      {          for(int i=0;i<n;i++)          {              if(isValid(a,n,index,i))              {                  a[index]=i;                  if(index == n-1)                  {                      num++;                      a[index]=0;                      return;                  }                  n_queens(a,n,index+1);                  a[index]=0;              }          }      }  public:    int totalNQueens(int n) {        int *a = new int[n];          memset(a,0,sizeof(int)*n);          n_queens(a,n,0);         return num;    }};



0 0