简体   繁体   中英

depth first search with 2D Array

I have an array like that :

0 0 0 0 0 0 0 0 0 0 0
0 0 1 0 0 0 1 0 0 0 0
0 1 1 1 1 0 0 1 0 1 0
0 1 1 0 1 0 0 0 0 1 1
0 0 0 1 1 0 0 0 1 1 0
0 0 0 0 0 0 0 0 0 0 0

And I want to group elements which are '1'.

So you see I have a classical dfs by using a stack. The question is, If I have a matrix like the above, what is the time complexity of this algorithm where n is the number of matrix elements. (Row*column).If it worse than O(N) (since I must traverse whole 2D array) which approach will help me to improve this algorithm?

Example of an O(n * log n) algorithm

(where n is the number of matrix elements)

The idea of the algorithm is as follows.

  1. Initialize a treeset of unhandled elements U by adding all matrix elements into it
  2. While U isn't yet empty, take any u from U and check it for its value
    • If u = '0' then just remove it, ie U := U \\ {u}
    • If u = '1' then start exploration DFS(u, U)


Where procedure DFS(u, U) uses the matrix to explore the '1' neighbours of u .

However, here comes the kicker, DFS(u, U) also removes every discovered element from U .


It is rather easy to understand and prove that this algorithm indeed always finishes in O(n * log n). Deleting an element from a treeset has worst-case complexity O(log n). Each DFS(u, U) run can visit at most |U| elements, and each element visited through any means is removed from U as the execution progresses. The algorithm terminates when U becomes empty.

Short summary

It is possible to produce an O(n^2) algorithm for example by running DFS on each element regardless of your previously attained knowledge. Using any mechanism ensuring that you don't run DFS on an already discovered group/island is likely to produce a superior algorithm.

Sorry that I can't analyze your own algorithm directly, but this may help you do it on your own.

The lower bound of the algorithm that you need to devise should be O(m+n) - I am considering the number of rows and columns as m and n respectively. This is because you need to traverse the whole 2D array anyway. If you are solving this using two for loops, this will take O(m+n) as well. For each element in your matrix, you will compare with other 4 adjacent elements and hence, the overall checking size is <= 4mn .

I think there is no better way to solve this in less than O(m+n) time.

Please note that in your question, if you are considering m+n = N then the complexity that I am referring to is O(N) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM