DFS

/* int check(参数)
{
    if(满足条件)
        return 1;
    return 0;
}

void dfs(int step)
{
        判断边界
        {
            相应操作
        }
        尝试每一种可能
        {
               满足check条件
               标记
               继续下一步dfs(step+1)
               恢复初始状态(回溯的时候要用到)
        }
}   
————————————————
版权声明:本文为CSDN博主「Xiyou_limeng」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/ldx19980108/article/details/76324307
 */

/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *returnColumnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */
#define DIRECTION 4

void dfs(int** image, int imageSize, int imageColSize, int x, int y, int* dx, int* dy, int newColor, int oldColor)
{
    if (image[x][y] != oldColor) {
        return;
    }
    image[x][y] = newColor;
    for (int k = 0; k < DIRECTION; k++) {
        int nextX = x + dx[k];
        int nextY = y + dy[k];
        if (nextX < 0 || nextX >= imageSize || nextY < 0 || nextY >= imageColSize) {
            continue;
        }
        dfs(image, imageSize, imageColSize, nextX, nextY, dx, dy, newColor, oldColor);
    }
    return;
}

int** floodFill(int** image, int imageSize, int* imageColSize, int sr, int sc, int newColor, int* returnSize, int** returnColumnSizes){
    if (!image || imageSize <= 0) {
        *returnSize = 0;
        return NULL;
    }
    *returnSize = imageSize;
    *returnColumnSizes = (int*)malloc(sizeof(int) * imageSize);
    for (int i = 0; i < imageSize; i++) {
        (*returnColumnSizes)[i] = imageColSize[0];
    }
    if (image[sr][sc] == newColor) {
        return image;
    }
    int* dx = (int*)malloc(sizeof(int) * DIRECTION);
    dx[0] = 0; dx[1] = 0; dx[2] = -1; dx[3] = 1;
    int* dy = (int*)malloc(sizeof(int) * DIRECTION);
    dy[0] = 1; dy[1] = -1; dy[2] = 0; dy[3] = 0;
    dfs(image, imageSize, imageColSize[0], sr, sc, dx, dy, newColor, image[sr][sc]);
    free(dx);
    free(dy);
    return image;
}

作者:Recurse
链接:https://leetcode-cn.com/problems/flood-fill/solution/733-tu-xiang-xuan-ran-cshi-xian-shen-du-you-xian-s/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值