Leetcode 733. Flood Fill | | Leetcode 733. Flood Fill 文章作者:Tyan博客:noahsnail.com | CSDN | 简书 1. Description 2. Solution Version 1 123456789101112131415161718192021222324class Solution {public: vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) { int rows = image.size(); int columns = image[0].size(); vector<vector<int>> flag(rows, vector<int>(columns)); int oldColor = image[sr][sc]; floodFill(image, sr, sc, newColor, oldColor, rows, columns, flag); return image; }private: void floodFill(vector<vector<int>>& image, int sr, int sc, int& newColor, int& oldColor, int& rows, int& columns, vector<vector<int>>& flag) { if(sr < 0 || sr == rows || sc < 0 || sc == columns || image[sr][sc] != oldColor || flag[sr][sc]) { return; } image[sr][sc] = newColor; flag[sr][sc] = 1; floodFill(image, sr + 1, sc, newColor, oldColor, rows, columns, flag); floodFill(image, sr - 1, sc, newColor, oldColor, rows, columns, flag); floodFill(image, sr, sc + 1, newColor, oldColor, rows, columns, flag); floodFill(image, sr, sc - 1, newColor, oldColor, rows, columns, flag); }}; Version 2 12345678910111213141516171819202122class Solution {public: vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) { int rows = image.size(); int columns = image[0].size(); int oldColor = image[sr][sc]; floodFill(image, sr, sc, newColor, oldColor, rows, columns); return image; }private: void floodFill(vector<vector<int>>& image, int sr, int sc, int& newColor, int& oldColor, int& rows, int& columns) { if(sr < 0 || sr == rows || sc < 0 || sc == columns || image[sr][sc] != oldColor || image[sr][sc] == newColor) { return; } image[sr][sc] = newColor; floodFill(image, sr + 1, sc, newColor, oldColor, rows, columns); floodFill(image, sr - 1, sc, newColor, oldColor, rows, columns); floodFill(image, sr, sc + 1, newColor, oldColor, rows, columns); floodFill(image, sr, sc - 1, newColor, oldColor, rows, columns); }}; Reference https://leetcode.com/problems/flood-fill/description/ 如果有收获,可以请我喝杯咖啡! 赏 微信打赏 支付宝打赏