Sunday, July 10, 2016

pond size

Get pond size given a matrix of heights.

Either use same matrix to mark already counted square or use a new matrix.
matrix:

0 2 1 0
0 1 0 1
1 1 0 1
0 1 0 1
pond-size(a):
    if a == null || a.length() == 0 || a[0].length() == 0:
        throw
    m = a.length()
    n = a[0].length()
    size = 0
    for i = 0, i < m, i++:
        for j = 0, j < n, j++:
            size += pond-size(a, i, m, j, n)
    // unmark
    if size > 0:
        for i = 0, i < m, i++:
            for j = 0, j < n, j++:
                if a[i][j] < 0:
                    a[i][j] = 0
    return size

pond-size(a, i, m, j, n):
    if i < 0 || i >= m:
        return 0
    if j < 0 || j >= n:
        return 0
    if a[i][j] != 0:
        return 0
    // mark to avoid double counting
    a[i][j] = -1
    size = 1
        + pond-size(a, i-1, m, j, n) 
        + pond-size(a, i+1, m, j, n) 
        + pond-size(a, i, m, j-1, n) 
        + pond-size(a, i, m, j+1, n) 
        + pond-size(a, i-1, m, j-1, n)
        + pond-size(a, i-1, m, j+1, n)
        + pond-size(a, i+1, m, j-1, n) 
        + pond-size(a, i+1, m, j+1, n)
    // cannot unmark here
    return size
[Hat tip to ctci]

No comments:

Post a Comment