Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayDeque;
- import java.util.Scanner;
- public class TheMatrix {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- int r = scanner.nextInt();
- int c = scanner.nextInt();
- scanner.nextLine();
- char[][] matrix = new char[r][c];
- for (int i = 0; i < r; i++) {
- matrix[i] = scanner.nextLine().replaceAll(" ", "").toCharArray();
- }
- char fillChar = scanner.nextLine().charAt(0);
- int fillRow = scanner.nextInt();
- int fillCol = scanner.nextInt();
- char toBeReplaced = matrix[fillRow][fillCol];
- ArrayDeque<int[]> stack = new ArrayDeque<>();
- stack.push(new int[]{fillRow, fillCol});
- while (!stack.isEmpty()) {
- int[] indexes = stack.pop();
- int row = indexes[0];
- int col = indexes[1];
- matrix[row][col] = fillChar;
- if (isInBounds(matrix, row + 1, col) && matrix[row + 1][col] == toBeReplaced) {
- stack.push(new int[]{row + 1, col});
- }
- if (isInBounds(matrix, row - 1, col) && matrix[row - 1][col] == toBeReplaced) {
- stack.push(new int[]{row - 1, col});
- }
- if (isInBounds(matrix, row, col + 1) && matrix[row][col + 1] == toBeReplaced) {
- stack.push(new int[]{row, col + 1});
- }
- if (isInBounds(matrix, row, col - 1) && matrix[row][col - 1] == toBeReplaced) {
- stack.push(new int[]{row, col - 1});
- }
- }
- //paintMatrix(matrix, toBeReplaced, fillChar, fillRow, fillCol);
- for (int i = 0; i < r; i++) {
- for (int j = 0; j < c; j++) {
- System.out.print(matrix[i][j]);
- }
- System.out.println();
- }
- }
- private static void paintMatrix(char[][] matrix, char toBeReplaced, char fillChar, int fillRow, int fillCol) {
- if (!isInBounds(matrix, fillRow, fillCol) || matrix[fillRow][fillCol] != toBeReplaced) {
- return;
- }
- matrix[fillRow][fillCol] = fillChar;
- paintMatrix(matrix, toBeReplaced, fillChar, fillRow - 1, fillCol);
- paintMatrix(matrix, toBeReplaced, fillChar, fillRow + 1, fillCol);
- paintMatrix(matrix, toBeReplaced, fillChar, fillRow, fillCol - 1);
- paintMatrix(matrix, toBeReplaced, fillChar, fillRow, fillCol + 1);
- }
- private static boolean isInBounds(char[][] matrix, int fillRow, int fillCol) {
- return fillRow >= 0 && fillRow < matrix.length && fillCol >= 0 && fillCol < matrix[fillRow].length;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment