【问题标题】:Check Adjacent Cells in 2D Array - Java检查二维数组中的相邻单元格 - Java
【发布时间】:2017-11-24 10:08:00
【问题描述】:

我有一个 14x14 大小的 JButton 二维数组。我用随机颜色绘制了 JButton,每次单击 JButton 时都需要找到具有相同颜色的相邻单元格。你们知道如何获得具有相同颜色的 JButton 单元的邻居吗? (请记住,一旦找到邻居,它也应该寻找邻居的邻居)。

【问题讨论】:

  • 你能提供一些代码吗?到目前为止有什么尝试吗?
  • 递归算法似乎合适。
  • 我有 4 种递归方法(南、西、东、北),它有效,但有时我收到 StackOverFlow 错误,我不知道为什么
  • 如果你能提供你现在的方法会有所帮助吗?
  • Board 类只有带有 JButtons 的网格?

标签: java arrays


【解决方案1】:

对我来说,这听起来像是一个简单的递归问题。 我对Java不熟悉,但由于它与C#非常相似,所以你应该可以很好地理解它。

List<Button> answer=new List<Button>();

private void ButtonClickEventHandler(object sender,EventArgs e)
{
    //I'm assuming you have a location property in each individual button,
    //and of course, the color.
    search(sender);
}

private void search(Button bt)
{
    int x=bt.x;
    int y=bt.y;
    bt.Visited=true;
    answer.Add(bt);
    if(x>0 && br[x-1][y].getColor()==bt.getColor() && !br[x-1][y].Visited) search(br[x-1,y]);
    if(x<14 && br[x+1][y].getColor()==bt.getColor() && !br[x+1][y].Visited) search(br[x+1,y]);
    if(y>0 && br[x][y-1].getColor()==bt.getColor() && !br[x][y-1].Visited) search(br[x,y-1]);
    if(y<14 && br[x][y+1].getColor()==bt.getColor() && !br[x][y+1].Visited) search(b[x,y+1]);
}

答案就是你的答案!原谅双关语!

【讨论】:

    【解决方案2】:
    public HashSet<JButton> lookForAdjancentButtons(int i, int j) {
        HashSet<JButton> set = new HashSet<>();
        set.add(board.getIndex(i, j));
        adjacentButtons(board.getColor(i, j), set, i, j);
        return set;
    }
    
    private void adjacentButtons(Color c, HashSet<JButton> set, int i, int j) {
        helperMethod(c, set, i - 1, j);
        helperMethod(c, set, i + 1, j);
        helperMethod(c, set, i, j - 1);
        helperMethod(c, set, i, j + 1);
    }
    
    private void helperMethod(Color c, HashSet<JButton> set, int i, int j) {
        if(i < 0 || j < 0 || i >= 14 || j >= 14) {
            return;
        }
        JButton b = board.getIndex(i, j);
        if(board.getColor(i, j) != c) {
            return;
        }
        if(!set.add(b)) {
            return;
        }
        adjacentButtons(c, set, i, j);
    }
    

    【讨论】:

      猜你喜欢
      • 2021-05-11
      • 2021-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-04
      • 2014-07-27
      • 2017-07-20
      相关资源
      最近更新 更多