Untitled
unknown
plain_text
a year ago
2.0 kB
4
Indexable
Never
import java.util.*; public class Main { public static void main(String[] args) throws Throwable { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int[][] image = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { image[i][j] = sc.nextInt(); } } int x = sc.nextInt(); int y = sc.nextInt(); int newColor = sc.nextInt(); int[][] ans = Solution.floodFill(image, x, y, newColor); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (j == m - 1) { System.out.print(ans[i][j] + "\n"); } else { System.out.print(ans[i][j] + " "); } } } } } class Solution { static void dfs(int row, int col, int[][] ans, int[][] image, int newColor, int delRow[], int delCol[], int iniColor) { ans[row][col] = newColor; int n = image.length; int m = image[0].length; for (int i = 0; i < 4; i++) { int nrow = row + delRow[i]; int ncol = col + delCol[i]; if (nrow >= 0 && nrow < n && ncol >= 0 && ncol < m && image[nrow][ncol] == iniColor && ans[nrow][ncol] != newColor) { dfs(nrow, ncol, ans, image, newColor, delRow, delCol, iniColor); } } } static int[][] floodFill(int[][] image, int x, int y, int newColor) { int iniColor = image[x][y]; int[][] ans = new int[image.length][image[0].length]; for (int i = 0; i < image.length; i++) { for (int j = 0; j < image[0].length; j++) { ans[i][j] = image[i][j]; } } int delRow[] = {-1, 0, 1, 0}; int delCol[] = {0, 1, 0, -1}; dfs(x, y, ans, image, newColor, delRow, delCol, iniColor); return ans; } }