【发布时间】:2021-02-12 23:34:14
【问题描述】:
我正在尝试使用递归和数组来确保矩阵是相邻的(水平、垂直或对角线),就像我已经开始的那样。如果它是相邻的,我希望它打印“A”。但是我遇到了麻烦,我们将不胜感激!
class Colony
{
public static void ExploreAndLabelColony(char grid[][], int i)
{
for (int j=0; j<grid[0].length; j++)
{
if (i == grid.length && j == grid[0].length) //prints colony
{
System.out.print(grid[i][j]);
}
else
{
if (grid[i][j] == '1') //checks if theres a 1 and checks if elements are adjacent and if they are print 'A'
{
if (i>0 && i + 1 < grid.length && j>0 && j + 1 < grid[0].length)
{
if (grid[i+1][j] == '1' || grid[i][j+1] == '1' || grid[i-1][j] == '1' || grid[i][j-1] == '1')
{
grid[i][j] = 'A';
System.out.println(grid[i][j]);
//ExploreAndLabelColony(grid, i+1);
}
}
else if(grid[i][j] == '0') //replaces 0 with '-'
{
grid[i][j] = '-';
ExploreAndLabelColony(grid, i+1);
}
}
//ExploreAndLabelColony(grid, i+1);
}
}
}
public static void main(String[] args)
{
char grid[][] = {{'0','0','0','1','1','0','1','1','0','0','0','1','1','1','0','1','1','1','0','1'},
{'1','0','0','0','0','1','0','0','0','1','0','0','0','0','0','1','1','1','1','1'},
{'0','1','0','0','1','0','0','0','1','0','1','0','0','0','0','0','0','1','1','1'},
{'1','1','1','0','0','1','0','1','0','0','0','0','1','0','1','1','0','1','1','0'},
{'0','1','1','1','0','1','1','1','0','1','0','0','1','0','1','0','1','1','0','1'}};
ExploreAndLabelColony(grid, 0);
}
}
【问题讨论】:
-
请定义邻接矩阵的含义。根据维基百科,“在图论和计算机科学中,adjacency matrix 是用于表示有限图的方阵。”你的矩阵不是正方形的。
-
元素需要水平、垂直或对角相邻@GilbertLeBlanc
-
部分元素或全部元素。我在您的代码中打印出矩阵,0 和 1 都不是完全连续的。
-
是的,我知道,它还有另一部分。但我很难找到哪些元素是相邻的。 @GilbertLeBlanc
-
在您定义足够的相邻之前,我无法帮助您,我可以通过查看网格来判断元素是否相邻。请充分定义问题,以便我可以理解您要做什么。您的网格在位置 4、7 有一个 1。