My solution to a “Daily Coding Problem” that I received in my mail today.

Given a 2-D matrix representing an image, a location of a pixel in the screen and a color C, replace the color of the given pixel and all adjacent same colored pixels with C.

For example, given the following matrix, and location pixel of (2, 2), and ‘G’ for green:

B B W
W W W
W W W
B B B

Becomes

B B G
G G G
G G G
B B B

Floodfill problem in Typescript

Here’s my solution in Typescript. I actually like this problem a lot 🙂 Brings back memories of my computer vision research at the University of New South Wales.

oneFiftyOne(matrix: string[][], i:number, j: number, target: string): string[][] {
    if(matrix == null) {
        return [];
    }
    if(i < 0 || i >= matrix.length || j <0 || j>= matrix[i].length) {
        return matrix;
    }
    if(matrix[i][j] == target) {
        matrix[i][j] = "C";
    } else {
        return matrix;
    }
    this.oneFiftyOne(matrix, i+1, j, target);
    this.oneFiftyOne(matrix, i-1, j, target);
    this.oneFiftyOne(matrix, i, j+1, target);
    this.oneFiftyOne(matrix, i, j-1, target);
    return matrix;
}

Get updates?

As usual, if you find any of my posts useful support me by  buying or even trying one of my apps on the App Store. 

https://mydaytodo.com/apps/

Also, if you can leave a review on the App Store or Google Play Store, that would help too.

Categories: Algorithms

0 Comments

Leave a Reply

Verified by MonsterInsights