LeetCode_Study_Plan/Algorithm
733. Flood Fill java
개발하는루루
2022. 12. 22. 14:46
https://leetcode.com/problems/flood-fill/description/
Flood Fill - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
class Solution {
int[][] image;
int m;
int n;
int newColor;
int oldColor;
boolean [][] visited;
public int[][] floodFill(int[][] image, int sr, int sc, int color) {
this.m = image.length;
this.n = image[0].length;
this.image = image;
this.oldColor = image[sr][sc];
this.newColor = color;
this.visited = new boolean[this.m][this.n];
dfs(sr, sc);
return this.image;
}
public void dfs(int i, int j) {
if (go_outside(i, j)) return;
if (this.visited[i][j]) return;
this.visited[i][j] = true;
if (this.image[i][j] != this.oldColor) return;
this.image[i][j] = this.newColor;
dfs(i+1, j);
dfs(i, j+1);
dfs(i-1, j);
dfs(i, j-1);
}
public boolean go_outside(int i, int j) {
if (i < 0 || i >= m || j < 0 || j >= n) {
return true;
}
return false;
}
}