日期:2014-05-20 浏览次数:20921 次
public static void main(String[] args) throws IOException { char[][] array = { {'r', 'g', 'r', 'g'}, {'r', 'r', 'r', 'r'}, {'g', 'r', 'g', 'r'}, {'g', 'g', 'g', 'g'} }; boolean[][] explored = new boolean[4][4]; List<Point> list = explore('r', array, explored, 0, 0); for(Point p : list){ System.out.println(p.x + "," + p.y); } } //探索从x,y点发散开与targetChar相同的点 private static List<Point> explore(char targetChar,char[][] array, boolean[][] explored, int x, int y){ //此点下表越界,直接返回null if(x < 0 || y < 0 || y >= array.length || x >= array[y].length) return null; //如果此点已经被探索过,或者与目标不同,直接返回null if(explored[y][x] || array[y][x] != targetChar) return null; //记录此点已被探索过 explored[y][x] = true; //将此点加入到list List<Point> pointList = new ArrayList<Point>(); pointList.add(new Point(x, y)); //取出周围所有点的坐标 Point[] aroundPoints = { new Point(x, y - 1), new Point(x, y + 1), new Point(x - 1, y), new Point(x + 1, y) }; //递归获取周围与周围所有联通点连接的点 for(Point point : aroundPoints){ List<Point> list = explore(targetChar, array, explored, point.x, point.y); if(list != null) pointList.addAll(list); } return pointList; }