这里我要做的是计算一 block 由随机黑色(0)和白色(1) block 组成的方板上相邻白色 block (以2为单位)的数量。白色 block 必须位于i+1,j
|| i-1,j
|| i,j+1
|| i,j-1
。从技术上讲,对角线不计算在内。我在下面提供了一个示例:
[1 0 1]
[1 1 0]
[0 1 0]
此处 count == 3
(0,0)(1,0) 和 (1,0)(1,1) 和 (1,1)(2,1)
这是我的代码:
public int count = 0;
boolean count(int x, int y, int[][] mat)
{
if(x<0 || y<0)
return false;
if(mat[x][y] == 0)
return false;
for(int i = x; i<mat.length; i++)
{
for(int j = y; j<mat[0].length; j++)
{
if(mat[i][j] == 1)
{
mat[i][j] = 0;
if(count(i-1,j,mat))
count++;
if(count(i,j-1,mat))
count++;
if(count(i+1,j,mat))
count++;
if(count(i,j+1,mat))
count++;
}
}
}
return true;
}
简单解释一下我在这里要做的事情:我要在棋盘上找到 1,当我找到一个时,我将其更改为 0,并检查其上、下、左、右是否为 1。直到我发现没有相邻的 1。我在这里缺少什么?我有一种感觉,我在不必要地循环。
最佳答案
这是一个没有递归的解决方案
for(int i = 0; i < mat.length; i++) {
for(int j = 0; j < mat[i].length; j++) {
if(mat[i][j] == 1) {
if(i < mat.length - 1 && mat[i+1][j] == 1) {
count++;
}
if(j < mat[i].length - 1 && mat[i][j+1] == 1) {
count++;
}
}
}
关于java - 棋盘游戏的递归代码困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9985747/