ProgrammingHardAccenture · Cognizant pattern

What will be the output of the following pseudocode (counting islands in a grid using flood-fill DFS)? (Grids are indexed from 0.)

What will be the output of the following pseudocode (counting islands in a grid using flood-fill DFS)? (Grids are indexed from 0.)
Integer grid[4][4] = {{1,1,0,0},{1,1,0,0},{0,0,1,0},{0,0,0,1}}
Boolean visited[4][4] = all false
Integer count = 0
Function dfs(Integer r, Integer c)
    if (out of bounds or visited[r][c] or grid[r][c] == 0)
        return
    end if
    visited[r][c] = true
    dfs(r+1,c); dfs(r-1,c); dfs(r,c+1); dfs(r,c-1)
End Function

for (each r from 0 to 3)
    for (each c from 0 to 3)
        if (grid[r][c] == 1 and not visited[r][c])
            count = count + 1
            dfs(r, c)
        end if
    end for
end for
Print count
  1. A. 2
  2. B. 4
  3. C. 3
  4. D. 1

Correct answer: C. 3

There are three separate connected groups of 1s: the 2x2 block in the top-left, the single 1 at (2,2), and the single 1 at (3,3) -- 3 islands total.

More Pseudocode and Code Tracing questions

Exams that ask this topic