The Wayback Machine - https://web.archive.org/web/20240907155328/https://www.geeksforgeeks.org/flood-fill-algorithm/
Open In App

Flood Fill Algorithm

Last Updated : 16 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a 2D image img[][] where each img[i][j] is an integer representing the color of that pixel, also given the location of a pixel (x, y) and a new color newClr, the task is to replace the existing color of the given pixel and all the adjacent same-colored pixels with the given newClr.

Example: 

Input: img[][] =
{ {1, 1, 1},
{1, 1, 0},
{1, 0, 1} }
x = 1, y = 1, newClr = 3
Output: img[][] =
{{3, 3, 3},
{3, 3, 0},
{3, 0, 1}}
Explanation: The value at arr[1][1] is 1. All connected pixels with the color 1 are replaced with 3

Input: img[][] =
{ {0, 0, 0},
{0, 1, 1} }
x = 1, y = 1, newClr = 1
Output: img[][] =
{{0, 0, 0},
{0, 1 , 1}}
Explanation: Old and new colors are same, so no change

Input:: arr[][] =
{ {2, 2, 2},
{2, 2, 2}, }
x = 0, y = 0, newClr = 1
Output: img[][] =
{{1, 1, 1},
{1, 1, 1}}}

Using DFS (O(m x n)) :

  • Change the color of the source row and source column with the given color
  • Do DFS in four directions
  • Do not forget to handle the case when previous and new colors are same.

Below is the implementation of the above approach:

C++
#include <bits/stdc++.h>
using namespace std;

void dfs(vector<vector<int>> &img, int x, int y, 
                      int prevClr, int newClr) {
    
    if (img[x][y] != prevClr)
       return;
  
    // Marking it as the new color
    img[x][y] = newClr;
    
    // Moving up, right, down and left one
    // by one.
    int n = img.size();
    int m = img[0].size();
    if(x - 1 >= 0l) 
        dfs(img, x - 1, y, prevClr, newClr);
    if(y + 1 < m) 
        dfs(img, x, y + 1, prevClr, newClr);
    if(x + 1 < n) 
        dfs(img, x + 1, y, prevClr, newClr);
    if(y - 1 >= 0) 
        dfs(img, x, y - 1, prevClr, newClr);
}

// FloodFill Function
void floodFill(vector<vector<int>>& img, 
              int x, int y, int newClr) {
                  
    int prevClr = img[x][y];
    if (prevClr == newClr)
       return;  
    dfs(img, x, y, prevClr, newClr);
}

// Driver code
int main() {
    vector<vector<int>> img = {{1, 1, 1}, 
                               {1, 1, 0}, 
                               {1, 0, 1}};
    // Co-ordinate provided by the user
    int x = 1;
    int y = 1;

    // New color that has to be filled
    int newClr = 3;
    floodFill(img, x, y, newClr);
    
    // Printing the updated img
    for (int i = 0; i < img.size(); i++) {
        for (int j = 0; j < img[0].size(); j++) {
            cout << img[i][j] << " ";
        }
        cout << endl;
    }

    return 0;
}
C
#include <stdio.h>

// Function to perform DFS
void dfs(int img[3][3], int x, int y, int prevClr, int newClr) {
    if (img[x][y] != prevClr)
        return;

    // Marking it as the new color
    img[x][y] = newClr;

    // Moving up, right, down and left one by one.
    if (x - 1 >= 0)
        dfs(img, x - 1, y, prevClr, newClr);
    if (y + 1 < 3)
        dfs(img, x, y + 1, prevClr, newClr);
    if (x + 1 < 3)
        dfs(img, x + 1, y, prevClr, newClr);
    if (y - 1 >= 0)
        dfs(img, x, y - 1, prevClr, newClr);
}

// FloodFill Function
void floodFill(int img[3][3], int x, int y, int newClr) {
    int prevClr = img[x][y];
    if (prevClr == newClr)
        return;
    dfs(img, x, y, prevClr, newClr);
}

// Driver code
int main() {
    int img[3][3] = {{1, 1, 1}, {1, 1, 0}, {1, 0, 1}};
    // Co-ordinate provided by the user
    int x = 1, y = 1;
    // New color that has to be filled
    int newClr = 3;
    floodFill(img, x, y, newClr);

    // Printing the updated img
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            printf("%d ", img[i][j]);
        }
        printf("\n");
    }
    return 0;
}
Java
import java.util.*;

public class Main {  

    public static void floodFill(List<List<Integer>> img, 
                                 int x, int y, int newClr) {
        int prevClr = img.get(x).get(y);
        if (prevClr == newClr) 
            return;
        dfs(img, x, y, prevClr, newClr);
    }

    public static void dfs(List<List<Integer>> img, int x,
                          int y, int prevClr, int newClr) {
      
        // Base case: if the current pixel is not the
        // same as the previous color
        if (img.get(x).get(y) != prevClr) {
            return;
        }

        // Marking it as the new color
        img.get(x).set(y, newClr);

        // Moving up, right, down, and left one by one
        int n = img.size();
        int m = img.get(0).size();
        if (x - 1 >= 0) {
            dfs(img, x - 1, y, prevClr, newClr);
        }
        if (y + 1 < m) {
            dfs(img, x, y + 1, prevClr, newClr);
        }
        if (x + 1 < n) {
            dfs(img, x + 1, y, prevClr, newClr);
        }
        if (y - 1 >= 0) {
            dfs(img, x, y - 1, prevClr, newClr);
        }
    }

    public static void main(String[] args) {
        List<List<Integer>> img = new ArrayList<>();
        img.add(Arrays.asList(1, 1, 1));
        img.add(Arrays.asList(1, 1, 0));
        img.add(Arrays.asList(1, 0, 1));

        // Co-ordinate provided by the user
        int x = 1;
        int y = 1;

        // New color that has to be filled
        int newClr = 3;
        floodFill(img, x, y, newClr);

        // Printing the updated img
        for (List<Integer> row : img) {
            for (int val : row) {
                System.out.print(val + " ");
            }
            System.out.println();
        }
    }
}
Python
def dfs(img, x, y, prev_clr, new_clr):
  
    # Base case: if the current pixel is not 
    # the same as the previous color
    if img[x][y] != prev_clr:
        return

    # Marking it as the new color
    img[x][y] = new_clr

    # Moving up, right, down, and left one by one
    n = len(img)
    m = len(img[0])
    if x - 1 >= 0:
        dfs(img, x - 1, y, prev_clr, new_clr)
    if y + 1 < m:
        dfs(img, x, y + 1, prev_clr, new_clr)
    if x + 1 < n:
        dfs(img, x + 1, y, prev_clr, new_clr)
    if y - 1 >= 0:
        dfs(img, x, y - 1, prev_clr, new_clr)

def flood_fill(img, x, y, new_clr):
    prev_clr = img[x][y]
    if prev_clr == new_clr:
        return
    dfs(img, x, y, prev_clr, new_clr)

# Driver code
img = [
    [1, 1, 1],
    [1, 1, 0],
    [1, 0, 1]
]

# Co-ordinate provided by the user
x = 1
y = 1

# New color that has to be filled
new_clr = 3
flood_fill(img, x, y, new_clr)

# Printing the updated img
for row in img:
    print(' '.join(map(str, row)))
C#
using System;
using System.Collections.Generic;

class Program {
    // Function to perform DFS
    static void Dfs(List<List<int>> img, int x, int y, int prevClr, int newClr) {
        if (img[x][y] != prevClr)
            return;

        // Marking it as the new color
        img[x][y] = newClr;

        // Moving up, right, down and left one by one.
        int n = img.Count;
        int m = img[0].Count;
        if (x - 1 >= 0)
            Dfs(img, x - 1, y, prevClr, newClr);
        if (y + 1 < m)
            Dfs(img, x, y + 1, prevClr, newClr);
        if (x + 1 < n)
            Dfs(img, x + 1, y, prevClr, newClr);
        if (y - 1 >= 0)
            Dfs(img, x, y - 1, prevClr, newClr);
    }

    // FloodFill Function
    static void FloodFill(List<List<int>> img, int x, int y, int newClr) {
        int prevClr = img[x][y];
        if (prevClr == newClr)
            return;
        Dfs(img, x, y, prevClr, newClr);
    }

    // Driver code
    static void Main() {
        List<List<int>> img = new List<List<int>> {
            new List<int> {1, 1, 1},
            new List<int> {1, 1, 0},
            new List<int> {1, 0, 1}
        };

        // Co-ordinate provided by the user
        int x = 1;
        int y = 1;

        // New color that has to be filled
        int newClr = 3;
        FloodFill(img, x, y, newClr);

        // Printing the updated img
        foreach (var row in img) {
            foreach (var val in row) {
                Console.Write(val + " ");
            }
            Console.WriteLine();
        }
    }
}
JavaScript
// Function to perform DFS
function dfs(img, x, y, prevClr, newClr) {
    if (img[x][y] !== prevClr)
        return;

    // Marking it as the new color
    img[x][y] = newClr;

    // Moving up, right, down, and left one by one.
    const n = img.length;
    const m = img[0].length;
    if (x - 1 >= 0)
        dfs(img, x - 1, y, prevClr, newClr);
    if (y + 1 < m)
        dfs(img, x, y + 1, prevClr, newClr);
    if (x + 1 < n)
        dfs(img, x + 1, y, prevClr, newClr);
    if (y - 1 >= 0)
        dfs(img, x, y - 1, prevClr, newClr);
}

// FloodFill Function
function floodFill(img, x, y, newClr) {
    const prevClr = img[x][y];
    if (prevClr === newClr)
        return;
    dfs(img, x, y, prevClr, newClr);
}

// Driver code
const img = [
    [1, 1, 1],
    [1, 1, 0],
    [1, 0, 1]
];
// Co-ordinate provided by the user
const x = 1, y = 1;
// New color that has to be filled
const newClr = 3;
floodFill(img, x, y, newClr);

// Printing the updated img
img.forEach(row => {
    console.log(row.join(' '));
});

Output
3 3 3 
3 3 0 
3 0 1 

Time Complexity: O(m*n)
Auxiliary Space: O(m*n), due to the recursive call stack.

Further Optimizations to the above code. We can check for the condition if (img[x][y] != prevClr) before making recursive calls. This will save some unnecessary recursive calls for the adjacent of the last nodes.

Using BFS (O(m x n)) :

The idea is to use BFS traversal to replace the color with the new color. 

  • Create an empty queue let’s say Q.
  • Push the starting location of the pixel as given in the input and apply the replacement color to it.
  • Iterate until Q is not empty and pop the front node (pixel position).
  • Check the pixels adjacent to the current pixel and push them into the queue if valid (had not been colored with replacement color).

Below is the implementation of the above approach:

C++
#include <bits/stdc++.h>
using namespace std;

// Fill the image img[x][y] and all its same colored
// adjacent with the given new color
void floodFill(vector<vector<int>>& img, int x, 
                              int y, int newClr) {
                                 
    queue<pair<int, int>> q;

    // Rows and columns of the display
    int m = img.size();
    int n = img[0].size();
   
    int prevClr = img[x][y];
    if (prevClr == newClr)
        return;

    // Append the position of starting pixel
    // of the component
    q.push({x, y});
    img[x][y] = newClr;

    // While the queue is not empty i.e. the 
    // whole component having prevClr color
    // is not colored with newClr color
    while (!q.empty()) {
        
        // Dequeue the front node
        x = q.front().first;
        y = q.front().second;
        q.pop();

        // Check if the adjacent pixels are valid 
        // and enqueue
        if (x + 1 < m && img[x + 1][y] == prevClr) {
            img[x + 1][y] = newClr;
            q.push({x + 1, y});
        }
        if (x - 1 >= 0 && img[x - 1][y] == prevClr) {
            img[x - 1][y] = newClr;
            q.push({x - 1, y});
        }
        if (y + 1 < n && img[x][y + 1] == prevClr) {
            img[x][y + 1] = newClr;
            q.push({x, y + 1});
        }
        if (y - 1 >= 0 && img[x][y - 1] == prevClr) {
            img[x][y - 1] = newClr;
            q.push({x, y - 1});
        }
    }
}

int main() {
    vector<vector<int>> img = {
        { 1, 1, 1 },
        { 1, 1, 0 },
        { 1, 0, 1 }
    };

    int x = 1, y = 1;
    int newClr = 3;
   
    floodFill(img, x, y, newClr);

    // Printing the updated img
    for (const auto& row : img) {
        for (int val : row) {
            cout << val << " ";
        }
        cout << endl;
    }

    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

#define M 3
#define N 3

// Fill the image img[x][y] and all its same colored
// adjacent with the given new color
void floodFill(int img[M][N], int x, int y, int newClr) {
    int m = M, n = N;
    int prevClr = img[x][y];
    if (prevClr == newClr) return;

    typedef struct { int x, y; } Point;
    Point queue[1000];
    int front = 0, rear = 0;

    queue[rear++] = (Point){x, y};
    img[x][y] = newClr;

    while (front < rear) {
        Point p = queue[front++];
        x = p.x; y = p.y;

        // Check if the adjacent pixels are valid and enqueue
        if (x + 1 < m && img[x + 1][y] == prevClr) {
            img[x + 1][y] = newClr;
            queue[rear++] = (Point){x + 1, y};
        }
        if (x - 1 >= 0 && img[x - 1][y] == prevClr) {
            img[x - 1][y] = newClr;
            queue[rear++] = (Point){x - 1, y};
        }
        if (y + 1 < n && img[x][y + 1] == prevClr) {
            img[x][y + 1] = newClr;
            queue[rear++] = (Point){x, y + 1};
        }
        if (y - 1 >= 0 && img[x][y - 1] == prevClr) {
            img[x][y - 1] = newClr;
            queue[rear++] = (Point){x, y - 1};
        }
    }
}

int main() {
    int img[M][N] = {
        { 1, 1, 1 },
        { 1, 1, 0 },
        { 1, 0, 1 }
    };
    int x = 1, y = 1;
    int newClr = 3;
    
    floodFill(img, x, y, newClr);

    // Printing the updated img
    for (int i = 0; i < M; i++) {
        for (int j = 0; j < N; j++) {
            printf("%d ", img[i][j]);
        }
        printf("\n");
    }
    return 0;
}
Java
import java.util.LinkedList;
import java.util.Queue;

public class GfG {

    // Fill the image img[x][y] and all its same colored
    // adjacent with the given new color
    public static void floodFill(int[][] img, int x, 
                                int y, int newClr) {
        Queue<int[]> q = new LinkedList<>();

        // Rows and columns of the display
        int m = img.length;
        int n = img[0].length;
   
        int prevClr = img[x][y];
        if (prevClr == newClr)
            return;

        // Append the position of the starting 
        // pixel of the component
        q.add(new int[]{x, y});
        img[x][y] = newClr;

        // While the queue is not empty, i.e., the 
        // whole component having prevClr color
        // is not colored with newClr color
        while (!q.isEmpty()) {
            
            // Dequeue the front node
            int[] pos = q.poll();
            x = pos[0];
            y = pos[1];

            // Check if the adjacent pixels are valid and enqueue
            if (x + 1 < m && img[x + 1][y] == prevClr) {
                img[x + 1][y] = newClr;
                q.add(new int[]{x + 1, y});
            }
            if (x - 1 >= 0 && img[x - 1][y] == prevClr) {
                img[x - 1][y] = newClr;
                q.add(new int[]{x - 1, y});
            }
            if (y + 1 < n && img[x][y + 1] == prevClr) {
                img[x][y + 1] = newClr;
                q.add(new int[]{x, y + 1});
            }
            if (y - 1 >= 0 && img[x][y - 1] == prevClr) {
                img[x][y - 1] = newClr;
                q.add(new int[]{x, y - 1});
            }
        }
    }

    public static void main(String[] args) {
        int[][] img = {
            { 1, 1, 1 },
            { 1, 1, 0 },
            { 1, 0, 1 }
        };

        int x = 1, y = 1;
        int newClr = 3;
   
        floodFill(img, x, y, newClr);

        // Printing the updated img
        for (int[] row : img) {
            for (int val : row) {
                System.out.print(val + " ");
            }
            System.out.println();
        }
    }
}
Python
from collections import deque

def floodFill(img, x, y, newClr):
    q = deque()

    # Rows and columns of the display
    m = len(img)
    n = len(img[0])
   
    prevClr = img[x][y]
    if prevClr == newClr:
        return

    # Append the position of the starting pixel 
    # of the component
    q.append((x, y))
    img[x][y] = newClr

    # While the queue is not empty, i.e., the whole 
    # component having prevClr color
    # is not colored with newClr color
    while q:
        # Dequeue the front node
        x, y = q.popleft()

        # Check if the adjacent pixels are valid and enqueue
        if x + 1 < m and img[x + 1][y] == prevClr:
            img[x + 1][y] = newClr
            q.append((x + 1, y))
        if x - 1 >= 0 and img[x - 1][y] == prevClr:
            img[x - 1][y] = newClr
            q.append((x - 1, y))
        if y + 1 < n and img[x][y + 1] == prevClr:
            img[x][y + 1] = newClr
            q.append((x, y + 1))
        if y - 1 >= 0 and img[x][y - 1] == prevClr:
            img[x][y - 1] = newClr
            q.append((x, y - 1))

# Driver code
img = [
    [1, 1, 1],
    [1, 1, 0],
    [1, 0, 1]
]

x = 1
y = 1
newClr = 3

floodFill(img, x, y, newClr)

# Printing the updated img
for row in img:
    print(' '.join(map(str, row)))
C#
using System;
using System.Collections.Generic;

class Program {
    // Fill the image img[x][y] and all its same colored
    // adjacent with the given new color
    static void FloodFill(int[,] img, int x, int y, int newClr) {
        Queue<(int, int)> q = new Queue<(int, int)>();
        int m = img.GetLength(0);
        int n = img.GetLength(1);
        int prevClr = img[x, y];
        if (prevClr == newClr) return;

        // Append the position of starting pixel
        q.Enqueue((x, y));
        img[x, y] = newClr;

        while (q.Count > 0) {
            (x, y) = q.Dequeue();

            // Check if the adjacent pixels are valid and enqueue
            if (x + 1 < m && img[x + 1, y] == prevClr) {
                img[x + 1, y] = newClr;
                q.Enqueue((x + 1, y));
            }
            if (x - 1 >= 0 && img[x - 1, y] == prevClr) {
                img[x - 1, y] = newClr;
                q.Enqueue((x - 1, y));
            }
            if (y + 1 < n && img[x, y + 1] == prevClr) {
                img[x, y + 1] = newClr;
                q.Enqueue((x, y + 1));
            }
            if (y - 1 >= 0 && img[x, y - 1] == prevClr) {
                img[x, y - 1] = newClr;
                q.Enqueue((x, y - 1));
            }
        }
    }

    static void Main() {
        int[,] img = {
            { 1, 1, 1 },
            { 1, 1, 0 },
            { 1, 0, 1 }
        };

        int x = 1, y = 1;
        int newClr = 3;
        
        FloodFill(img, x, y, newClr);

        // Printing the updated img
        for (int i = 0; i < img.GetLength(0); i++) {
            for (int j = 0; j < img.GetLength(1); j++) {
                Console.Write(img[i, j] + " ");
            }
            Console.WriteLine();
        }
    }
}
JavaScript
// Fill the image img[x][y] and all its same colored
// adjacent with the given new color
function floodFill(img, x, y, newClr) {
    const q = [];
    const m = img.length;
    const n = img[0].length;
    const prevClr = img[x][y];
    if (prevClr === newClr) return;

    q.push({ x, y });
    img[x][y] = newClr;

    while (q.length > 0) {
        const { x, y } = q.shift();

        // Check if the adjacent pixels are valid and enqueue
        if (x + 1 < m && img[x + 1][y] === prevClr) {
            img[x + 1][y] = newClr;
            q.push({ x: x + 1, y });
        }
        if (x - 1 >= 0 && img[x - 1][y] === prevClr) {
            img[x - 1][y] = newClr;
            q.push({ x: x - 1, y });
        }
        if (y + 1 < n && img[x][y + 1] === prevClr) {
            img[x][y + 1] = newClr;
            q.push({ x, y: y + 1 });
        }
        if (y - 1 >= 0 && img[x][y - 1] === prevClr) {
            img[x][y - 1] = newClr;
            q.push({ x, y: y - 1 });
        }
    }
}

// Test the flood fill function
const img = [
    [1, 1, 1],
    [1, 1, 0],
    [1, 0, 1]
];
const x = 1, y = 1, newClr = 3;
floodFill(img, x, y, newClr);

// Printing the updated img
img.forEach(row => {
    console.log(row.join(' '));
});

Output
3 3 3 
3 3 0 
3 0 1 

Time Complexity: O(m * n)
Auxiliary Space: O(m * n)

The BFS approach would work better in general as it does not require overhead of recursion.



Previous Article
Next Article

Similar Reads

Difference Between Flood-fill and Boundary-fill Algorithm
Flood-fill Algorithm: Flood fill algorithm is also known as a seed fill algorithm. It determines the area which is connected to a given node in a multi-dimensional array. This algorithm works by filling or recolouring a selected area containing different colours at the inside portion and therefore the boundary of the image. It is often illustrated
3 min read
Flood fill Algorithm - how to implement fill() in paint?
In MS-Paint, when we take the brush to a pixel and click, the color of the region of that pixel is replaced with a new selected color. Following is the problem statement to do this task. Given a 2D screen, location of a pixel in the screen and a color, replace color of the given pixel and all adjacent same colored pixels with the given color. Examp
15+ min read
Boundary Fill Algorithm
Prerequisite : Flood fill algorithm, Scan-line polygon fillingIntroduction : Boundary Fill Algorithm starts at a pixel inside the polygon to be filled and paints the interior proceeding outwards towards the boundary. This algorithm works only if the color with which the region has to be filled and the color of the boundary of the region are differe
5 min read
Edge Relaxation Property for Dijkstra’s Algorithm and Bellman Ford's Algorithm
In the field of graph theory, various shortest path algorithms especially Dijkstra’s algorithm and Bellmann-Ford’s algorithm repeatedly employ the use of the technique called Edge Relaxation. The idea of relaxation is the same in both algorithms and it is by understanding, the 'Relaxation property' we can fully grasp the working of the two algorith
4 min read
Difference between Greedy Algorithm and Divide and Conquer Algorithm
Greedy algorithm and divide and conquer algorithm are two common algorithmic paradigms used to solve problems. The main difference between them lies in their approach to solving problems. Greedy Algorithm:The greedy algorithm is an algorithmic paradigm that follows the problem-solving heuristic of making the locally optimal choice at each stage wit
3 min read
Algorithm Library | C++ Magicians STL Algorithm
For all those who aspire to excel in competitive programming, only having a knowledge about containers of STL is of less use till one is not aware what all STL has to offer. STL has an ocean of algorithms, for all &lt; algorithm &gt; library functions : Refer here.Some of the most used algorithms on vectors and most useful one's in Competitive Prog
7 min read
What is the stupidest sorting algorithm? (Worst Sorting Algorithm)
Bogo sort stands out as the undisputed champion of stupidity. Unlike other sorting algorithms that follow a structured approach, Bogo sort relies on sheer luck and randomness to achieve its goal. How Bogo Sort Works?Bogo sort operates on the following principle: Randomly shuffle the elements in the list.Check if the list is sorted.If the list is no
2 min read
Difference Between Dijkstra's Algorithm and A* Search Algorithm
Dijkstra's Algorithm and A* Algorithm are two of the most widely used techniques. Both are employed to the find the shortest path between the nodes in a graph but they have distinct differences in their approaches and applications. Understanding these differences is crucial for the selecting the appropriate algorithm for the given problem. What is
3 min read
Z algorithm (Linear time pattern searching Algorithm)
This algorithm efficiently locates all instances of a specific pattern within a text in linear time. If the length of the text is "n" and the length of the pattern is "m," then the total time taken is O(m + n), with a linear auxiliary space. It is worth noting that the time and auxiliary space of this algorithm is the same as the KMP algorithm, but
13 min read
Karatsuba algorithm for fast multiplication using Divide and Conquer algorithm
Given two binary strings that represent value of two integers, find the product of two strings. For example, if the first bit string is "1100" and second bit string is "1010", output should be 120. For simplicity, let the length of two strings be same and be n. A Naive Approach is to follow the process we study in school. One by one take all bits o
15+ min read
Fill 8 numbers in grid with given conditions
Place the numbers 1, 2, 3, 4, 5, 6, 7, 8 into the eight circles in the figure given below, in such a way that no number is adjacent to a number that is next to it in the sequence. For example, 1 should not be adjacent to 2 but can be adjacent to 3, 4, 5, 6, 7, 8. Similarly for others. Naive Algorithm The Naive Algorithm is to generate all possible
6 min read
Minimum number of square tiles required to fill the rectangular floor
Given a rectangular floor of (M X N) meters is to be paved with square tiles of (s X s). The task is to find the minimum number of tiles required to pave the rectangular floor. Constraints: It's allowed to cover the surface larger than the floor, but the floor has to be covered.It's not allowed to break the tiles.The sides of tiles should be parall
9 min read
Minimum time required to fill a cistern using N pipes
Given the time required by a total of N+1 pipes where N pipes are used to fill the Cistern and a single pipe is used to empty the Cistern. The task is to Calculate the amount of time in which the Cistern will get filled if all the N+1 pipes are opened together. Examples: Input: n = 2, pipe1 = 12 hours, pipe2 = 14 hours, emptypipe = 30 hours Output:
5 min read
Minimum number of bottles required to fill K glasses
Given N glasses having water, and a list A of each of their capacity. The task is to find the minimum number of bottles required to fill out exactly K glasses. The capacity of each bottle is 100 units. Examples: Input: N = 4, K = 3, arr[] = {200, 150, 140, 300} Output: 5 We have to fill out exactly 3 glasses. So we fill out 140, 150, 200 whose sum
5 min read
Fill missing entries of a magic square
Given a 3X3 matrix mat with it's left diagonal elements missing (set to 0), considering the sum of every row, column and diagonal of the original matrix was equal, the task is to find the missing diagonal elements and print the original matrix. Examples: Input: mat[][] = {{0, 7, 6}, {9, 0, 1}, {4, 3, 0}} Output: 2 7 6 9 5 1 4 3 8 Row sum = Column s
7 min read
Find a way to fill matrix with 1's and 0's in blank positions
Given an N * M matrix mat[][] which consists of two types of characters '.' and '_'. The task is to fill the matrix in positions where it contains '.' with 1's and 0's. Fill the matrix in such a way that no two adjacent cells contain the same number and print the modified matrix.Examples: Input: mat[][] = {{'.', '_'}, {'_', '.'}} Output: 1 _ _ 1Inp
5 min read
Fill the missing numbers in the array of N natural numbers such that arr[i] not equal to i
Given an unsorted array arr[] consisting of N natural numbers and the missing numbers as 0 such that arr[i] ? i, the task is to find and fill these missing numbers without changing the initial order. Please note that the array can contain numbers from 1 to N only once. Examples: Input: arr[] = {7, 4, 0, 3, 0, 5, 1} Output: 7 4 6 3 2 5 1 Explanation
9 min read
Minimum time required to fill the entire matrix with 1's
Given a matrix of size N consisting of 0's and 1's, the task is to find the minimum time required to fill the entire matrix with 1's. Every 1 at an instant in the matrix, can convert all 0's to 1 in its eight adjacent cells,i.e. a 1 present at (i,j) can convert all 0's to 1 at positions (i, j-1), (i, j+1), (i-1, j), (i+1, j), (i-1, j-1), (i-1, j+1)
13 min read
Queries to count minimum flips required to fill a binary submatrix with 0s only
Given a binary matrix mat[][] of size M * N and Q queries of the form {pi, pj, qi, qj}, the task for each query is to count the number of 0s in the submatrix from the cell (pi, pj) to (qi, qj). Examples: Input: mat[][] = {{0, 1, 0, 1, 1, 1, 0}, {1, 0, 1, 1, 1, 0, 1}, {1, 1, 0, 0, 1, 1, 0}, {1, 1, 1, 1, 1, 0, 1}, {0, 0, 1, 0, 1, 1, 1}, {1, 1, 0, 1,
14 min read
Fill an empty 2D Matrix with integers from 1 to N*N filled diagonally
Given an integer N, the task is to fill a matrix M of size NxN, starting from the main diagonal and then alternating between the lower and upper triangular diagonals, in an increasing fashion such that each number from 1 to N2 appears only once. Examples: Input: N = 4 Output: 1 8 13 16 5 2 9 14 11 6 3 10 15 12 7 4 Explanation: First filling the mai
7 min read
Tensorflow.js tf.fill() Function
Tensorflow.js is an open-source library for creating machine learning models in Javascript that allows users to run the models directly in the browser. The tf.fill() is a function defined in the class tf.Tensor. It is used to create a tensor that is filled with a scalar value. Syntax: tf.fill( shape, value, dtype ) Parameters: shape: It's an array
2 min read
Check if it’s possible to completely fill every container with same ball
Given two arrays, arr[ ] C of containers and arr[ ] B of balls, the task is to find if it's possible to completely fill every container with the given balls, if each container can only store balls of the same type. In array C, C[i] stores the maximum number of balls that the i-th container can store. In array B, B[i] stores the type of the i-th bal
7 min read
Minimize water to fill all tanks connected by given circuit
Given N tanks connected like a tree, the connections between them in an array Edge[][], and the capacity of each tank in the array cap[], the task is to find the minimum amount of water required to pour into the given tank such that all the tanks are filled. Note: When a tank is filled, the remaining amount of water is equally distributed among the
9 min read
Count ways to fill Array with distinct elements with given limitation
Given an array arr[] of size N and you need to fill another empty array of size N with positive integers. Each element in the given array denotes the maximum positive integer you can choose to fill the empty array. The task is to find the number of ways to fill the empty array such that all elements are distinct. Examples: Input: N = 1, arr[] = {6}
6 min read
Maximize score to fill Matrix when score of a step is count of adjacent filled cells
Given two integers N and M that denotes the number of rows and columns of a matrix that is initially empty, the task is to fill all the empty cells and find the maximum score while filling them when the score to fill a cell is the same as the count of adjacent filled cells. Examples: Input: N=2, M=3Output: 7Explanation: Matrix after applying 3 oper
14 min read
Minimum time required to fill given N slots
Given an integer N which denotes the number of slots, and an array arr[] consisting of K integers in the range [1, N] . Each element of the array are in the range [1, N] which represents the indices of the filled slots. At each unit of time, the index with filled slot fills the adjacent empty slots. The task is to find the minimum time taken to fil
13 min read
Minimize the number of iterations to Fill a Matrix with Ones
Given a matrix with dimensions N x M, filled with zeroes except for one position at coordinates X and Y containing '1'. In one iteration, '1' can be filled in the 4 neighboring elements of a cell containing '1'. This means if there are 2 cells with '1', their neighboring cells can be marked as '1' in the next iteration. Find the minimum number of i
5 min read
Ways to fill N positions using M colors such that there are exactly K pairs of adjacent different colors
Given three integers N, M and K. The task is to find the number of ways to fill N positions using M colors such that there are exactly K pairs of different adjacent colors. Examples: Input: N = 3, M = 2, K = 1 Output: 4 Let the colors be 1 and 2, so the ways are: 1, 1, 2 1, 2, 2 2, 2, 1 2, 1, 1 The above 4 ways have exactly one pair of adjacent ele
12 min read
Fill the Matrix by following the given conditions
Given a matrix A[][] of N rows and M columns. Some of the elements of the matrix are -1, which denotes that cell is empty. Then your task is to check if it is possible to fill empty cells in such a way that each row and column is sorted. If yes, then output matrix after filling cells, else output -1. If there are multiple solutions, then print any
11 min read
Fill two instances of all numbers from 1 to n in a specific way
Given a number n, create an array of size 2n such that the array contains 2 instances of every number from 1 to n, and the number of elements between two instances of a number i is equal to i. If such a configuration is not possible, then print the same.Examples: Input: n = 3 Output: res[] = {3, 1, 2, 1, 3, 2} Input: n = 2 Output: Not Possible Inpu
10 min read
Article Tags :
Practice Tags :