Skip to lesson

Grids as graphs

A 2D grid acts as an implicit graph where each cell represents a vertex connecting to adjacent neighbours.

Implicit graph structure and direction vectors

An implicit graph is a graph whose edges are not stored but worked out when needed, such as a grid where each cell is joined to the cells beside it.

A grid of R rows and C columns is an implicit graph: each cell (r, c) is a vertex joined to the cells above, below, left and right. We never build an adjacency list for it.

Example 1 · Direction Array Iteration with Boundary Checks

Main.javaJava
public class Main {    static final int[] DR = {-1, 1, 0, 0};    static final int[] DC = {0, 0, -1, 1};
    static void printNeighbors(int r, int c, int rows, int cols) {        System.out.print("Valid neighbors of (" + r + "," + c + "): ");        for (int k = 0; k < 4; k++) {            int nr = r + DR[k];            int nc = c + DC[k];            if (nr >= 0 && nr < rows && nc >= 0 && nc < cols) {                System.out.print("(" + nr + "," + nc + ") ");            }        }        System.out.println();    }
    public static void main(String[] args) {        printNeighbors(0, 0, 3, 3);        printNeighbors(1, 1, 3, 3);    }}
Output
Valid neighbors of (0,0): (1,0) (0,1) 
Valid neighbors of (1,1): (0,1) (2,1) (1,0) (1,2) 

What this code does

  • Direction offsets DR and DC generate up, down, left, and right steps.
  • Boundary condition prevents generating out-of-bounds negative or excessive indices.
  • Corner cell (0,0) yields 2 valid neighbours while center cell (1,1) yields 4.

Compute neighbours on the fly with direction arrays dr and dc, looping k from 0 to 3 for four directions (size 8 if diagonals count).

Check bounds before reading matrix[nr][nc]: a move is valid only when 0 <= nr < R and 0 <= nc < C. Skipping the check throws ArrayIndexOutOfBoundsException.

Connected components on grids: Number of islands

The Number of Islands problem treats a binary grid as an undirected graph. Cells with value 1 represent land vertices, while cells with 0 represent water. An island is a connected component of land cells joined orthogonally.

Example 2 · Number of Islands Using DFS

Main.javaJava
public class Main {    static int numIslands(char[][] grid) {        if (grid == null || grid.length == 0) return 0;        int rows = grid.length, cols = grid[0].length;        int islands = 0;
        for (int r = 0; r < rows; r++) {            for (int c = 0; c < cols; c++) {                if (grid[r][c] == '1') {                    islands++;                    dfs(grid, r, c, rows, cols);                }            }        }        return islands;    }
    static void dfs(char[][] grid, int r, int c, int rows, int cols) {        if (r < 0 || r >= rows || c < 0 || c >= cols || grid[r][c] != '1') return;        grid[r][c] = '0'; // Mark visited        dfs(grid, r - 1, c, rows, cols);        dfs(grid, r + 1, c, rows, cols);        dfs(grid, r, c - 1, rows, cols);        dfs(grid, r, c + 1, rows, cols);    }
    public static void main(String[] args) {        char[][] grid = {            {'1', '1', '0', '0'},            {'1', '1', '0', '0'},            {'0', '0', '1', '0'},            {'0', '0', '0', '1'}        };        System.out.println("Total islands: " + numIslands(grid));    }}
Output
Total islands: 3

What this code does

  • Top-left 2x2 cluster forms a single connected island component.
  • Cells (2,2) and (3,3) each form separate individual islands.
  • DFS sinks visited land cells to 0 to avoid duplicate counting.

Brute force search without visited tracking revisits cells infinitely, causing call stack overflow. To solve it efficiently, loop over every grid cell (r, c) from row 0 to R - 1. Whenever you encounter an unvisited land cell, increment island counter by one. Then launch BFS or DFS from that cell to traverse all reachable land cells. Mark visited cells by replacing 1 with 0 in-place or using a boolean array. Total time complexity is O(R * C) because each cell is inspected at most twice. Auxiliary space complexity is O(R * C) for the queue or recursive call stack.

Flood fill and paint bucket algorithms

Flood fill recolors one cell and every connected cell of the same colour, spreading outward from a starting cell like the paint bucket tool.

Flood fill changes the colour of a target region starting from an origin coordinate. Graphics software uses this exact algorithm for paint bucket tool fills. Given a starting cell (sr, sc) and new colour, record original colour oldColor = image[sr][sc].

Flood fill from the top-left corner

Step 1 of 8

Row0123
01110
11100
21011
30011
Flood fill from row 0, column 0 (colour 1) with the new colour 2. Only connected cells of colour 1 will change.

Example 3 · Flood Fill Algorithm in Java

Main.javaJava
import java.util.Arrays;
public class Main {    static int[][] floodFill(int[][] image, int sr, int sc, int newColor) {        int oldColor = image[sr][sc];        if (oldColor != newColor) {            dfs(image, sr, sc, oldColor, newColor);        }        return image;    }
    static void dfs(int[][] image, int r, int c, int oldColor, int newColor) {        if (r < 0 || r >= image.length || c < 0 || c >= image[0].length) return;        if (image[r][c] != oldColor) return;
        image[r][c] = newColor;        dfs(image, r - 1, c, oldColor, newColor);        dfs(image, r + 1, c, oldColor, newColor);        dfs(image, r, c - 1, oldColor, newColor);        dfs(image, r, c + 1, oldColor, newColor);    }
    public static void main(String[] args) {        int[][] image = {            {1, 1, 1},            {1, 1, 0},            {1, 0, 1}        };        floodFill(image, 1, 1, 2);        for (int[] row : image) {            System.out.println(Arrays.toString(row));        }    }}
Output
[2, 2, 2]
[2, 2, 0]
[2, 0, 1]

What this code does

  • Starting at (1,1) with colour 1 changes to replacement colour 2.
  • Orthogonally connected matching colour cells are coloured recursively.
  • Unconnected cell at (2,2) remains unaffected because colour 0 blocks it.

If oldColor already equals new colour, return immediately to prevent infinite recursion. Otherwise, traverse all 4-directional neighbours sharing oldColor using DFS or BFS. Update image[r][c] to the new colour upon visit. Boundary checks guard every step against out-of-bounds indices and mismatched colours. Real-world applications include region filling, maze traversal, and image segmentation.

Next step

Check your understanding

10 quick questions