Here you can find the source of findConnectedComponents(int[][] image)
public static int[][] findConnectedComponents(int[][] image)
//package com.java2s; /***************************************************************************** ** ANGRYBIRDS AI AGENT FRAMEWORK//from w ww . j av a2 s. c o m ** Copyright (c) 2013,XiaoYu (Gary) Ge, Stephen Gould,Jochen Renz ** Sahan Abeyasinghe, Jim Keys, Kar-Wai Lim, Zain Mubashir, Andrew Wang, Peng Zhang ** All rights reserved. **This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. **To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/ *or send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA. *****************************************************************************/ import java.awt.*; import java.util.*; public class Main { public static int[][] findConnectedComponents(int[][] image) { // renumbered components final int nHeight = image.length; final int nWidth = image[0].length; int n = -1; int[][] cc = new int[nHeight][nWidth]; for (int y = 0; y < nHeight; y++) { for (int x = 0; x < nWidth; x++) { cc[y][x] = -1; } } // iterate over all pixels for (int y = 0; y < nHeight; y++) { for (int x = 0; x < nWidth; x++) { // skip negative pixels if (image[y][x] == -1) continue; // check if component was already numbered if (cc[y][x] != -1) continue; // number the new component n = n + 1; Queue<Point> q = new LinkedList<Point>(); q.add(new Point(x, y)); cc[y][x] = n; while (!q.isEmpty()) { Point p = q.poll(); if ((p.y > 0) && (image[p.y - 1][p.x] == image[p.y][p.x]) && (cc[p.y - 1][p.x] == -1)) { q.add(new Point(p.x, p.y - 1)); cc[p.y - 1][p.x] = n; } if ((p.x > 0) && (image[p.y][p.x - 1] == image[p.y][p.x]) && (cc[p.y][p.x - 1] == -1)) { q.add(new Point(p.x - 1, p.y)); cc[p.y][p.x - 1] = n; } if ((p.y < nHeight - 1) && (image[p.y + 1][p.x] == image[p.y][p.x]) && (cc[p.y + 1][p.x] == -1)) { q.add(new Point(p.x, p.y + 1)); cc[p.y + 1][p.x] = n; } if ((p.x < nWidth - 1) && (image[p.y][p.x + 1] == image[p.y][p.x]) && (cc[p.y][p.x + 1] == -1)) { q.add(new Point(p.x + 1, p.y)); cc[p.y][p.x + 1] = n; } } } } return cc; } }