mardi 3 novembre 2015

I am trying to write a recursive function in c++ and it keeps causing a stack overflow

So i am trying to write a recursive function to count all of the spaces on a grid of characters. It is for a project in which i have to write a program that calculates the score of a simplified game of Go. The board i'm given looks like this http://ift.tt/1Nd3gxr] . All of the open spaces are surrounded. I am supposed to ultimately find which player surrounded more open space. I am not sure how to find how many spaces are surrounded by a specific character. I think i know how to count all of the spaces though. I wrote this code to do so http://ift.tt/1l77EHL] . I call it from an object of the class that it is in that was declared on the stack, like so; game.countSpaces(0, 0). No matter what, it always causes a stack overflow. I have tried debugging it and it never reaches the last two function calls. It just cycles the first two until visual studio finally crashes. Can anyone explain why this won't work to find the number of spaces? Why does it cause the stack to overflow? Also could you give me a hint about how to go after here to count only the spaces one player has surrounded? If not that's fine. But i really really want to know why my initial space counting function doesn't work. p. s. I didn't declare count because it is a member of the class.

void GoScorer::countSpaces(int row, int col)
{
    if((row < 0) || (row >= BOARDSIZE))
            return;
    if((col < 0) || (col >= BOARDSIZE))
            return;
    if (board[row][col] != ' ')
            return;

    count++;

    countSpaces((row - 1), col);
    countSpaces((row + 1), col);
    countSpaces(row, (col - 1));
    countSpaces(row, (col + 1));
    return;
}

  BWB  BW WB BW    
  BWB  BW WB BW    
  BWBBBBW WB BW    
  BWWWWWW WBBBWWWWW
  BBW  WW WWBBBBBBB
   BWWWWW  WB      
   BBBBBWWWWB      
BBBBB  BBWWWBB BBBB
WWWWB   BW WBBBWWWW
  WWB    BWWWB BW  
  WBBBBBBBWBBBBW   
  WWWWWWWWWB  BW   
  WW   WWWWB  BWWWW
WWWWW     WB  BBBBB
BBBBWWW   WB       
  BBBBW   WB  BBBBB
  BBBBWWW WB  BWWWW
     BBBW WB  BW   
       BW WB  BW

Aucun commentaire:

Enregistrer un commentaire