Did anyone think the solution is wrong?


  • 0
    Z

    I tried my code with size 5, and it returned 14 different solutions.
    But the expected answer showed that should be 10.
    I checked manually and found the extra answer in my output is all right.
    Here is my code in scala, you can try that with size 5:

    def solveNQueens(n: Int): List[List[String]] = {
    
      def isSafe(pos:Int,poses:List[Int]):Boolean = {
        if (poses.exists(_==pos)) return false                 
        if (math.abs(poses.head-pos)<2) return false
        true
      }
    
      def QueensList(rowNo:Int):List[List[Int]] = {
        if (rowNo==0) {
          val res = scala.collection.mutable.ListBuffer.empty[List[Int]]  
          for (i<- 0 to n-1) res+=List(i)
          return res.toList
        }
    
        val res = scala.collection.mutable.ListBuffer.empty[List[Int]]    
        val preResults = QueensList(rowNo - 1)
        for (preResult <- preResults; i<-0 to n-1) {
          if (isSafe(i,preResult)) res += (i::preResult)                    
        }
        res.toList
      }
    
      val buf = scala.collection.mutable.ListBuffer.empty[Array[Array[String]]] 
      val queensPoses = QueensList(n-1)
      for (posList<-queensPoses) {
        val empBoard = Array.fill(n)(Array.fill(n)(".")) 
        var rowNo = 0
        for (pos<-posList) {empBoard(rowNo)(pos)="Q";rowNo+=1}
        buf += empBoard
      }
      //buf.map(board=>board.map(row=>row.toList).toList.foldLeft(List[String]())(_:::_)).toList           
      buf.map(board => board.map(row => row.foldRight("")(_+_)).toList).toList
    
      }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.