int flood_fill_board (unsigned short pos, unsigned char color) { if (!on_board (pos) || get_point_board (pos) == color) { return 0; } empty_stack (&parse_stack); int ret_val = 0; unsigned char orig_color = get_point_board (pos); set_point_board (pos, color); ++ret_val; push_pos_stack (&parse_stack, pos); while (pop_pos_stack (&parse_stack, &pos)) { ret_val += flood_fill_helper (NORTH (pos), orig_color, color); ret_val += flood_fill_helper (SOUTH (pos), orig_color, color); ret_val += flood_fill_helper (EAST (pos), orig_color, color); ret_val += flood_fill_helper (WEST (pos), orig_color, color); } return ret_val; }
// This function receives the image and conduct floodfill operation in place. void flood_fill(std::vector<std::string> & image, int row, int col, char filler) { if (!isValid(image, row, col) || image[row][col] == filler) { std::cerr << "Invlid input " << row << " and " << col << std::endl; exit(1); } // construct a visited matrix filled with false std::vector<std::vector<bool> > visited; for (unsigned int i = 0; i < image.size(); i++) { std::vector<bool> tmp(image[i].size(), false); visited.push_back(tmp); } flood_fill_helper(image, row, col, filler, visited, image[row][col]); }
// This helper function receives the image // and fill the specified commponent using // dfs recurrsively. void flood_fill_helper(std::vector<std::string> & image, int row, int col, char filler, std::vector<std::vector<bool> > visited, char color) { image[row][col] = filler; visited[row][col] = true; int dx[4] = {0, -1, 1, 0}; int dy[4] = {1, 0, 0, -1}; // we iteratively check all entries around the element // and dfs recursively to fill it for (unsigned int i = 0; i < 4; i++) { int nrow = row + dx[i]; int ncol = col + dy[i]; if (isValid(image, nrow, ncol) && image[nrow][ncol] == color && !visited[nrow][ncol]) { flood_fill_helper(image, nrow, ncol, filler, visited, color); } } }