相关疑难解决方法(0)

Leetcode上“岛屿数量”的DFS和BFS时空复杂性

是问题描述。建议的前两个解决方案涉及DFS和BFS。这个问题涉及第一种方法:DFS和BFS。

我将问题陈述包括在此处,以便于阅读。

Given a 2d grid map of '1's (land) and '0's (water), count the number of 
islands. An island is surrounded by water and is formed by connecting adjacent
lands horizontally or vertically. You may assume all four edges of the grid are 
all surrounded by water.

    Example 1:

    Input:
    11110
    11010
    11000
    00000

    Output: 1


    Example 2:

    Input:
    11000
    11000
    00100
    00011

    Output: 3
Run Code Online (Sandbox Code Playgroud)

对于DFS和BFS的时间复杂度为何同时存在,我不清楚O(rows * columns)。我看到网格只是充满0的情况是怎么回事-我们只需要检查每个单元格即可。但是,DFS方法是否不会增加搜索时间?即使我们通过0在dfs方法中将访问的单元格标记为来标记它们,由于两个外部循环,我们仍然会重新访问所有单元格。如果在行数和列数较大的大网格中dfs的时间复杂度为O(n),那么时间复杂度不是O(行*列* max [rows,cols])吗?此外,是不一样的情况下,与BFS方法,即它是O(rows * …

algorithm big-o breadth-first-search depth-first-search

5
推荐指数
1
解决办法
4836
查看次数