You have probably used MS Paint or Photoshop. When you select the "Paint Bucket" tool and click on a red circle, the entire circle turns blue. It stops exactly at the borders. How does the computer know which pixels to change?
It uses a graph traversal algorithm. This technique is called flood fill. Each pixel is a node, and adjacent pixels of the same color are connected. You start at one pixel and spread outward until you hit a boundary or different color.