Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Uprajnenie;
- import java.util.LinkedList;
- import java.util.Queue;
- import java.util.Scanner;
- public class TheMatrix {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- int rows = scanner.nextInt();
- int cols = scanner.nextInt();
- scanner.nextLine(); // Consume newline
- char[][] matrix = new char[rows][cols];
- for (int i = 0; i < rows; i++) {
- String[] row = scanner.nextLine().split(" ");
- for (int j = 0; j < cols; j++) {
- matrix[i][j] = row[j].charAt(0);
- }
- }
- char fillChar = scanner.next().charAt(0);
- int startRow = scanner.nextInt();
- int startCol = scanner.nextInt();
- fillMatrix(matrix, fillChar, startRow, startCol);
- // Print the filled matrix
- for (int i = 0; i < rows; i++) {
- for (int j = 0; j < cols; j++) {
- System.out.print(matrix[i][j]);
- }
- System.out.println();
- }
- }
- private static void fillMatrix(char[][] matrix, char fillChar, int startRow, int startCol) {
- char startChar = matrix[startRow][startCol];
- int rows = matrix.length;
- int cols = matrix[0].length;
- Queue<Integer> queue = new LinkedList<>();
- queue.add(startRow);
- queue.add(startCol);
- while (!queue.isEmpty()) {
- int row = queue.poll();
- int col = queue.poll();
- if (matrix[row][col] != startChar) {
- continue;
- }
- matrix[row][col] = fillChar;
- if (isValid(row - 1, col, rows, cols)) {
- queue.add(row - 1);
- queue.add(col);
- }
- if (isValid(row + 1, col, rows, cols)) {
- queue.add(row + 1);
- queue.add(col);
- }
- if (isValid(row, col - 1, rows, cols)) {
- queue.add(row);
- queue.add(col - 1);
- }
- if (isValid(row, col + 1, rows, cols)) {
- queue.add(row);
- queue.add(col + 1);
- }
- }
- }
- private static boolean isValid(int row, int col, int rows, int cols) {
- return row >= 0 && row < rows && col >= 0 && col < cols;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement