微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决常见的 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 举报,一经查实,本站将立刻删除。