常见的 DFS 问题“连接单元格”或“找到岛”但只能找到矩形

问题描述

我刚刚学习了一种称为 DFS 的算法,当我观看视频时,最流行的使用 DFS 的实践或示例是 Connected Cells 或 find island one,它是具有 0 和 1 的二维数组。但我真的希望要知道我是否只希望岛形状为矩形(或正方形),我该怎么办或如何更改程序中的 if 或 for 循环。这是我正在查看的代码

    // No. of rows and columns 
    static final int ROW = 3,COL = 5; 

    // A function to check if a given cell (row,col) can 
    // be included in DFS 
    boolean isSafe(int M[][],int row,int col,boolean visited[][]) 
    { 
        // row number is in range,column number is in range 
        // and value is 1 and not yet visited 
        return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && (M[row][col] == 1 && !visited[row][col]); 
    } 

    // A utility function to do DFS for a 2D boolean matrix. 
    // It only considers the 8 neighbors as adjacent vertices 
    void DFS(int M[][],boolean visited[][]) 
    { 
        // These arrays are used to get row and column numbers 
        // of 8 neighbors of a given cell 
        int rowNbr[] = new int[] { -1,-1,1,1 }; 
        int colNbr[] = new int[] { -1,1 }; 

        // Mark this cell as visited 
        visited[row][col] = true; 

        // Recur for all connected neighbours 
        for (int k = 0; k < 8; ++k) 
            if (isSafe(M,row + rowNbr[k],col + colNbr[k],visited)) 
                DFS(M,visited); 
    } 

    // The main function that returns count of islands in a given 
    // boolean 2D matrix 
    int countIslands(int M[][]) 
    { 
        boolean visited[][] = new boolean[ROW][COL]; 
        int count = 0; 
        for (int i = 0; i < ROW; ++i) 
            for (int j = 0; j < COL; ++j) 
                if (M[i][j] >= 100 && !visited[i][j]) 
                { 
                    DFS(M,i,j,visited); 
                    ++count; 
                } 

        return count; 
    } 

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)