我正在尝试解决这个递归练习:
在一个多维棋盘中(M x N),每个元素都可以为空或为满。
“污点”大小是指相邻且值为'x'的元素数量。
例如,这是一个多维数组(数字是行/列号)
| 0 | 1 | 2 | 3 | 4 |
0 | | x | | | x |
1 | x | | | x | x |
2 | | | x | x | |
3 | x | | | | |
4 | x | x | x | | |
有三个位置:
- 行 (0,1),(1,0) - 大小为2
- 行 (0,4),(1,3),(1,4),(2,2),(2,3) - 大小为5
- 行 (3,0),(4,0),(4,1),(4,2) - 大小为4
我们需要编写一个递归函数,其签名为:
public static int stain (char [][] mat, int row, int col)
该方法将获取一行和一列,并计算从该位置开始的污渍大小,如果没有污渍,则返回0。
我尝试编写该方法来解决它,但似乎我的做法有点混乱...你能指导我正确的方向吗?我不是在寻找直接的答案。
谢谢。
一些备注:
- 您可以更改数组以解决此问题。 - 您可以使用重载。 - 您不能使用任何循环。 - 您不能使用静态变量。
我的代码:
function stain (char[][] mat, int row, int col)
{
int col_len = mat.length;
int row_len = mat[0].length;
if (row < 0 || col < 0 || row >= row_len || col >= col_len)
return 0;
if (mat[row][col] != 'x')
return 0;
mat[row][col] = 'y';
// Count current
int count = 1;
// Go Left
count += stain (mat, row, col-1);
// Go Right
count += stain (mat, row, col+1);
// Go Up
count += stain (mat, row+1, col);
// Go Down
count += stain (mat, row-1, col);
// Go UpperRight
count += stain (mat, row+1, col+1);
// Go UpperLeft
count += stain (mat, row-1, col+1);
// Go DownRight
count += stain (mat, row+1, col-1);
// Go DownLeft
count += stain (mat, row-1, col-1);
return count;
}