a working non-recursive floodfill algorithm written in C?

后端 未结 12 2224
日久生厌
日久生厌 2020-12-02 23:39

I\'ve been trying to find a working floodfill algorithm. Of the many algorithms I\'ve tried only the \'recursive line fill\' one behaves exactly as it should with the major

12条回答
  •  無奈伤痛
    2020-12-03 00:35

    Below is my BFS based iterative c++ method for the flood fill problem:

    // M is the input matrix, with every entry(pixel) have a color
    // represented with an integer value.
    // (x, y) row and column of seed point respectively
    // k: The new color to fill the seed and its adjacent pixels
    void floodFill(vector> &M, int x, int y, int k) {
        queue> nodeQ;
        nodeQ.push({x, y});
        int oldCol = M[x][y];
        while(!nodeQ.empty()) {
            pair currNode = nodeQ.front();
            nodeQ.pop();
            if(M[currNode.first][currNode.second] == oldCol) {
                M[currNode.first][currNode.second] = k;
                if(currNode.first > 0) nodeQ.push({currNode.first-1, currNode.second});
                if(currNode.first < (M.size()-1)) nodeQ.push({currNode.first+1, currNode.second});
                if(currNode.second > 0) nodeQ.push({currNode.first, currNode.second-1});
                if(currNode.second < (M[0].size()-1)) nodeQ.push({currNode.first, currNode.second+1});
            }
        }
    }
    

提交回复
热议问题