title: Matlab NQueens Algorithm Recursion
body: <p>For an assignment I was tasked to devise an NQueens algorithm using Matlab and recursion. So the way I've set it up is I have 2 helper functions isValid, which tests for valid placement, and recursiveQueen, which places or removes a queen from a MxM board of 0's and adds one or removes 1 from every possible move the queen can make. For sake of space I removed the add functions from the recursiveQueen function, but all it does is add or subtract 1 in 8 directions. </p>
  
  <p>The main problem I am having is in my solveNQ function getting it to go to the next column if no solutions are found for the preceding row. I've broken my steps down to 6 things:</p>
  
  <p>1)Place a queen in the first row</p>
  
  <p>2)Place a queen in the next row next valid position</p>
  
  <p>3)Repeat step 2 until no valid placement is found for row</p>
  
  <p>4)Remove the queen from the last row</p>
  
  <p>5)Place the queen in the next valid spot of the row</p>
  
  <p>6)Repeat step 1-5 until all rows contain a queen (I haven't coded this step in)</p>
  
  <pre><code>function out = NQueens(m) %main function
  board = zeros(m,m); %intializes board
  out = solveNQ(1,board) %recursive function
  end
  
  function out = solveNQ(col,board)
  n = length(board);
  out = false; %returns false if no solutions found
  if col &gt; n  
  else
      for i = col:n 
          for j = 1:n
              if isValid(board,i,j)
                  board = recursiveQueen(board,i,j,'place') %place queen
                  out = solveNQ(col+1,board) %recursive call
              end
          end
          board = recursiveQueen(board,i-1,col,'remove') %if no valid placement for row
          out = solveNQ(col-1,board) %try again
      end
  end
  end
  
  
  function out = isValid(board,row,col)
      if board(row,col) == 0
         out = true;
      else
         out = false;
  end
  
  function board = recursiveQueen(board,row,col,move)
  board = goRight(board,row,col,move); %right
  board = goLeft(board,row,col,move); %left
  board = goDown(board,row,col,move); %down
  board = goUp(board,row,col,move); %up
  board = goRightUp(board,row,col,move); %diagnol up right
  board = goLeftUp(board,row,col,move); %diagnol up left
  board = goRightDown(board,row,col,move); %diagnol right down
  board = goLeftDown(board,row,col,move); %diagnol left down
      if strcmp(move,'place') %places queen
          board(row,col) = -1; 
      elseif strcmp(move,'remove') %removes queen
          board(row,col) = 0;
       end
  end
  </code></pre>