使用深度优先搜索来遍历矩阵以找出渗透

时间:2013-03-14 23:49:18

标签: java recursion matrix depth-first-search

我正在尝试编写一个布尔方法,如果矩阵是“满”或不是

,它将返回

(完整网站是一个开放式网站,可通过一系列相邻(左,右,上,下)开放网站连接到顶行的开放网站。)

表示网格,true =开放网站

我还在学习递归,我在某处读到DFS用于解决迷宫,所以我正在尝试这条路线......

现在我刚刚添加了一个相同的大小矩阵来跟踪该点是否已被访问过。我想弄清楚一种方法。给出一个初始点,看看我是否可以使用递归遍历到顶行..

我知道这是错的,有人的帮助可以指导我。我现在卡住了,我有点沮丧。这是我到目前为止所得到的

private boolean [][] grid;
private boolean [][] visited;
private int size;

public boolean isFull(int i, int j)
{
    int row = i-1;
    int col = j-1;


    //base cases        
    if(row < 0 || row > size || col < 0 || col > size) {
        throw new IndexOutOfBoundsException("Out of Bounds Exception");
    }

    if(row == 0) {
        return true;
    }

    if(visited[row][col]) {
        return false;
    }

    visited[row][col] = true;

    //top
    isFull(row, col-1);
    //bot
    isFull(row, col+1);
    //left
    isFull(row-1, col);
    //right
    isFull(row+1, col);

    return false;
}

1 个答案:

答案 0 :(得分:1)

这个website使用java和递归方法来检查网格是否渗透。还有另一种方法可以使用“Union Find”算法进行检查:

/*
    To start and for convenience, set each elements's
    id to its own index value
*/

//number of elements to test
int n; 

int[] treeSize = new int[n];
int[] id = new int[n];
for(int i = 0; i < n; i++){
    id[i] = i;
    treeSize[i] = 1;
}

void makeUnion(int p, int q){
    /*
       Connect smaller tree to the bigger one by
       making root of the smaller tree the child of
       the root of the bigger tree.
    */
    int pRoot = getRoot(p);
    int qRoot = getRoot(q);

    treeSize[pRoot] < treeSize[qRoot] ?
      id[pRoot] = qRoot, treeSize[qRoot] += treeSize[pRoot] :
      id[qRoot] = pRoot, treeSize[pRoot] += treeSize[qRoot] ;
}

bool connected(int p, int q){
  return getRoot(p) == getRoot(q);
 }

int getRoot(int i){
   /*
     Transverse through parent
     pointers in the tree
     until root is reached
   */
   while(i != id[i]){         //check if root
      id[i] = id[ id[i] ];  //flatten tree a bit(path compression by 1/2) points to grand-parent now
      i = id[i];                          //move up one level
   }
   return i;
}

您遍历整个网格并使用makeUnion连接两个位置(如果它们是开放的和相邻的)并使用connected检查底部和顶部是否已连接。

相关问题