我正在读12年级的compsci,并且遇到了关于递归的问题。这个问题的内容要求我在给定起始行和列的情况下找到一个房间中开放空间的数量。

“ X”代表墙壁,“ O”代表开放空间。开放空间仅在彼此相邻而不是对角线时计数。

给定此房间布局,myHouse.roomSize(1,1)将返回21,而myHouse.roomSize(5,9)将返回5。如果起始行或列是墙,则将返回0。

 012345678901234567
0XXXXXXXXXXXXXXXXXX
1XOOOOOOXOOOOOOOOOX
2XXXXOOOXOOOOOOOOOX
3XOOOOOOXOOOOOOOOOX
4XOOXXXXOXXXOOOOOOX
5XOOOOXXOOOOXXXOOXX
6XXXXXXXXXXXXXXXXXX


如果有人可以给我一些技巧,以解决递归问题

我将非常感谢,谢谢。

编辑:到目前为止,这是我尝试解决的尝试,
Edit2(立即格式化):将迷宫更改为布局

public int roomSize (int row, int col)
{
    if (layout[row][col] == 'X'|| layout [row][col]== '*')
        return 0;
    if (layout[row][col] == 'O')
    {
    layout[row][col]='*';
    return 1 + roomSize(row + 1, col);
    return 1 + roomSize(row, col + 1);
    return 1 + roomSize(row - 1, col);
    return 1 + roomSize(row, col - 1);
    layout[row][col]='O';
    }
}

最佳答案

伪代码帮助不想为您做事

int roomSize(int row, int col)
|   bool [x][y] v; //Array to stored visited values x is the width of the maze y is the height
|     set all bools in v to false
|    return doRoomSize(row,col, v)
end

int doRoomSize(int r, int c, v)
|    if( v[r][c] = true ||  layout [r][c]='X' )
|     | return 0
|    end-if
|    //Now we know that its a good value
|
|This is a maze type problem so what you need to do is


int roomSize(int row, int col)
|   bool [x][y] v; //Array to stored visited values x is the width of the maze y is the height
|     set all bools in v to false
|    return doRoomSize(row,col, v)
end

int doRoomSize(int r, int c, v)
|    if( v[r][c] = true ||  layout [r][c]='X' )
|     | return 0
|    end-if
|    //Now we know that its a good value
|    v[r][c] = true; // we have seen this point so we addit to visted
|      int n=1;
|    //Check left
|         n+= doRoomSize(r-1, c)
|    //Check right
|        n+=doRoomSize(r+1,c)
|   //Check up
|        n+=doRoomSize(r,c-1)
|  // Check down
|        n+=doRoomSize(r,c+1)
|     return n;
end-method

关于java - 如何递归搜索房屋布局中的开放空间?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22826449/

10-09 07:59