Counting Islands In Matrix Of Boolean Code objective: Read a txt file, parse it into a matrix and count (and also print) the number of unique "islands" in the map formed by the matrix.

0 = Sea;
1 = Land;
Islands are orthogonal groups of land.

testfile.txt :

5 9
00000
00010
10000
01101
10000
00100
01001
10010
01101


Python code:

# Reads the file and creates the matrix map.
with open('testfile.txt') as f:
    w = int(f.read(1))
    f.read(1)
    h = int(f.read(1))
    f.read(1)
    map = [[2 for x in range(w)] for y in range(h)]
    for y in range(h):
        for x in range(w):
            map[y][x] = int(f.read(1))
        f.read(1)

# Swipes the matrix map after NEW land chunks.
def swipe():
    counter = 0
    for x in range(h):
        for y in range(w):
            if map[x][y] == 1:
                counter += 1
                landInSight(map, x, y, 99)
    print(counter)

# Recursive function to hide any land attached to a chunk already swiped.
def landInSight(m, h, w, c):
    if m[h][w] == 1:
        m[h][w] = c
        if w &lt; len(m[0]) - 1: landInSight(m, h, w + 1, c)
        if h &lt; len(m) - 1: landInSight(m, h + 1, w, c)
        if w &gt; 0: landInSight(m, h, w - 1, c)
        if h &gt; 0: landInSight(m, h - 1, w, c)

# Calls the swipe function.
swipe()


It is a very simple code, but I took way too long coding it. This is my first "program" using Python and although it works, it seems too rough. I am looking for any constructive inputs from Python people.
First of all, your solution for this task looks pretty elegant, from my point of view. I would just provide minor comments to optimize this code.



Your input data is a boolean matrix, so instead of keeping every value as a byte you can use just one bit. For that purpose you can use bitarray module.



Another point, that you are loading whole matrix to the memory. It can be too expensive in certain circumstances. I can suggest one stream-based solution which will calculate a number of islands in dynamic manner. This method was discussed here.