Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayDeque;
- import java.util.Arrays;
- import java.util.Scanner;
- public class TheMatrix {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- int[] ints = Arrays.stream(scanner.nextLine().split("\\s")).mapToInt(Integer::parseInt).toArray();
- int rows = ints[0];
- int cols = ints[1];
- char[][] matrix = new char[rows][cols];
- for (int i = 0; i < rows; i++) {
- String[] strings = scanner.nextLine().split("\\s");
- for (int j = 0; j < cols; j++) {
- matrix[i][j] = strings[j].charAt(0);
- }
- }
- char fillChar = scanner.nextLine().charAt(0);
- ints = Arrays.stream(scanner.nextLine().split("\\s")).mapToInt(Integer::parseInt).toArray();
- int startRow = ints[0];
- int startCol = ints[1];
- char startChar = matrix[startRow][startCol];
- ArrayDeque<String> stack = new ArrayDeque<>();
- stack.push(startRow + " " + startCol);
- while (!stack.isEmpty()) {
- String node = stack.pop();
- ints = Arrays.stream(node.split("\\s")).mapToInt(Integer::parseInt).toArray();
- startRow = ints[0];
- startCol = ints[1];
- matrix[startRow][startCol] = fillChar;
- if (canReachUp(matrix, startRow - 1, startCol, startChar)) {
- stack.push(startRow - 1 + " " + startCol);
- }
- if (canReachDown(matrix, startRow + 1, startCol, startChar)) {
- stack.push(startRow + 1 + " " + startCol);
- }
- if (canReachLeft(matrix, startRow, startCol - 1, startChar)) {
- stack.push(startRow + " " + (startCol - 1));
- }
- if (canReachRight(matrix, startRow, startCol + 1, startChar)) {
- stack.push(startRow + " " + (startCol + 1));
- }
- }
- for (char[] chars : matrix) {
- for (char aChar : chars) {
- System.out.print(aChar);
- }
- System.out.println();
- }
- }
- private static boolean canReachUp(char[][] matrix, int row, int col, char startChar) {
- return row >= 0 && matrix[row][col] == startChar;
- }
- private static boolean canReachDown(char[][] matrix, int row, int col, char startChar) {
- return row < matrix.length && matrix[row][col] == startChar;
- }
- private static boolean canReachLeft(char[][] matrix, int row, int col, char startChar) {
- return col >= 0 && matrix[row][col] == startChar;
- }
- private static boolean canReachRight(char[][] matrix, int row, int col, char startChar) {
- return col < matrix[row].length && matrix[row][col] == startChar;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement