Lakes in Berland (Codeforces 723D)
Tags: Implement, dsu

The map of Berland is a rectangle of the size n × m, which consists of cells of size 1 × 1. Each cell is either land or water. The map is surrounded by the ocean. Lakes are the maximal regions of water cells, connected by sides, which are not connected with the ocean. Formally, lake is a set of water cells, such that it's possible to get from any cell of the set to any other without leaving the set and moving only to cells adjacent by the side, none of them is located on the border of the rectangle, and it's impossible to add one more water cell to the set such that it will be connected with any other cell.You task is to fill up with the earth the minimum number of water cells so that there will be exactly k lakes in Berland. Note that the initial number of lakes on the map is not less than k. 

Input: The first line of the input contains three integers n, m and k (1 ≤ n, m ≤ 50, 0 ≤ k ≤ 50) — the sizes of the map and the number of lakes which should be left on the map.The next n lines contain m characters each — the description of the map. Each of the characters is either '.' (it means that the corresponding cell is water) or '*' (it means that the corresponding cell is land).It is guaranteed that the map contain at least k lakes.

Output: In the first line print the minimum number of cells which should be transformed from water to land. In the next n lines print m symbols — the map after the changes. The format must strictly follow the format of the map in the input data (there is no need to print the size of the map). If there are several answers, print any of them. It is guaranteed that the answer exists on the given data.

Note: In the first example there are only two lakes — the first consists of the cells (2, 2) and (2, 3), the second consists of the cell (4, 3). It is profitable to cover the second lake because it is smaller. Pay attention that the area of water in the lower left corner is not a lake because this area share a border with the ocean. 

Sample Inputs:
5 4 1
****
*..*
****
**.*
..**

3 3 0
***
*.*
***

Sample Outputs:
1
****
*..*
****
****
..**

1
***
***
***

Solution (Python):
def fillLake(s, visited, graph):
    visited.add(s)
    graph[s[0]][s[1]] = '*'
    directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
    for d in directions:
        cellRow = s[0] + d[0]
        cellCol = s[1] + d[1]
        if cellRow in range(len(graph)) and cellCol in range(len(graph[0])):
            if graph[cellRow][cellCol] == '.' and (cellRow, cellCol) not in visited:
                fillLake((cellRow, cellCol), visited, graph)

def connectedToOcean(cellRow, cellCol, graph):
    return cellRow == 0 or cellRow == len(graph) - 1 or cellCol == 0 or (cellCol == len(graph[0]) - 1)

def getValidLakeSize(s, visited, graph):
    validLake = True
    if connectedToOcean(s[0], s[1], graph):
        validLake = False
    size = 1
    stack = [s]
    visited.add(s)
    directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
    while len(stack) > 0:
        currCellPos = stack.pop()
        for d in directions:
            cellRow = currCellPos[0] + d[0]
            cellCol = currCellPos[1] + d[1]
            if cellRow in range(len(graph)) and cellCol in range(len(graph[0])):
                if graph[cellRow][cellCol] == '.' and (cellRow, cellCol) not in visited:
                    if not connectedToOcean(cellRow, cellCol, graph):
                        size += 1
                        stack.append((cellRow, cellCol))
                        visited.add((cellRow, cellCol))
                    else:
                        validLake = False
    return size if validLake else -1

def main():
    (n, m, k) = map(int, input().split())
    berland = []
    for i in range(n):
        line = list(input())
        berland.append(line)
    lakes = dict()
    visited = set()
    numLakes = 0
    for i in range(n):
        for j in range(m):
            if berland[i][j] == '.' and (i, j) not in visited:
                size = getValidLakeSize((i, j), visited, berland)
                if size != -1:
                    if size not in lakes:
                        lakes[size] = [(i, j)]
                    else:
                        lakes[size].append((i, j))
                    numLakes += 1
    lakes = dict(sorted(lakes.items()))
    filledCell = set()
    for size in lakes:
        while len(lakes[size]) > 0 and numLakes > k:
            tempLake = lakes[size].pop()
            fillLake(tempLake, filledCell, berland)
            numLakes -= 1
    print(len(filledCell))
    for line in berland:
        print(''.join(line))
if __name__ == '__main__':
    main()

Solution (Python):
def fillLake(s, visited, graph):
    visited.add(s)
    graph[s[0]][s[1]] = '*'
    directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
    for d in directions:
        cellRow = s[0] + d[0]
        cellCol = s[1] + d[1]
        if cellRow in range(len(graph)) and cellCol in range(len(graph[0])):
            if graph[cellRow][cellCol] == '.' and (cellRow, cellCol) not in visited:
                fillLake((cellRow, cellCol), visited, graph)

def connectedToOcean(cellRow, cellCol, graph):
    return cellRow == 0 or cellRow == len(graph) - 1 or cellCol == 0 or (cellCol == len(graph[0]) - 1)

def getValidLakeSize(s, visited, graph):
    validLake = True
    if connectedToOcean(s[0], s[1], graph):
        validLake = False
    size = 1
    stack = [s]
    visited.add(s)
    directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
    while len(stack) > 0:
        currCellPos = stack.pop()
        for d in directions:
            cellRow = currCellPos[0] + d[0]
            cellCol = currCellPos[1] + d[1]
            if cellRow in range(len(graph)) and cellCol in range(len(graph[0])):
                if graph[cellRow][cellCol] == '.' and (cellRow, cellCol) not in visited:
                    if not connectedToOcean(cellRow, cellCol, graph):
                        size += 1
                        stack.append((cellRow, cellCol))
                        visited.add((cellRow, cellCol))
                    else:
                        validLake = False
    return size if validLake else -1

def main():
    (n, m, k) = map(int, input().split())
    berland = []
    for i in range(n):
        line = list(input())
        berland.append(line)
    lakes = dict()
    visited = set()
    numLakes = 0
    for i in range(n):
        for j in range(m):
            if berland[i][j] == '.' and (i, j) not in visited:
                size = getValidLakeSize((i, j), visited, berland)
                if size != -1:
                    if size not in lakes:
                        lakes[size] = [(i, j)]
                    else:
                        lakes[size].append((i, j))
                    numLakes += 1
    lakes = dict(sorted(lakes.items()))
    filledCell = set()
    for size in lakes:
        while len(lakes[size]) > 0 and numLakes > k:
            tempLake = lakes[size].pop()
            fillLake(tempLake, filledCell, berland)
            numLakes -= 1
    print(len(filledCell))
    for line in berland:
        print(''.join(line))
if __name__ == '__main__':
    main()

Solution (Python):
dr = [-1, 0, 0, 1]
dc = [0, -1, 1, 0]

def isValid(r, c):
    return r in range(n) and c in range(m)

def DFS(sr, sc):
    is_sea = False
    count = 1
    stack = [(sr, sc)]
    visited[sr][sc] = True
    if sr == 0 or sc == 0 or sr == n - 1 or (sc == m - 1):
        is_sea = True
    while stack:
        (r, c) = stack.pop()
        for i in range(4):
            nr = r + dr[i]
            nc = c + dc[i]
            if isValid(nr, nc) and (not visited[nr][nc]) and (terrain[nr][nc] == '.'):
                if nr == 0 or nc == 0 or nr == n - 1 or (nc == m - 1):
                    is_sea = True
                else:
                    count += 1
                visited[nr][nc] = True
                stack.append((nr, nc))
    if not is_sea:
        size.append((count, sr, sc))

def fix(sr, sc):
    stack = [(sr, sc)]
    terrain[sr][sc] = '*'
    while stack:
        (r, c) = stack.pop()
        for i in range(4):
            nr = r + dr[i]
            nc = c + dc[i]
            if isValid(nr, nc) and terrain[nr][nc] == '.':
                terrain[nr][nc] = '*'
                stack.append((nr, nc))
(n, m, k) = map(int, input().split())
size = []
visited = [[False] * m for i in range(n)]
terrain = []
for i in range(n):
    terrain.append(list(input()))
for i in range(n):
    for j in range(m):
        if terrain[i][j] == '.' and (not visited[i][j]):
            DFS(i, j)
size.sort()
ans = 0
for i in range(len(size) - k):
    ans += size[i][0]
for i in range(len(size) - k):
    fix(size[i][1], size[i][2])
print(ans)
for row in terrain:
    print(''.join(row))