kalinikov

12. The Matrix

Dec 19th, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class TheMatrix {
  4. public static void main(String[] args) {
  5. Scanner scanner = new Scanner(System.in);
  6.  
  7. int r = scanner.nextInt();
  8. int c = scanner.nextInt();
  9. scanner.nextLine();
  10.  
  11. char[][] matrix = new char[r][c];
  12.  
  13. for (int i = 0; i < r; i++) {
  14. matrix[i] = scanner.nextLine().replaceAll(" ", "").toCharArray();
  15. }
  16.  
  17. char fillChar = scanner.nextLine().charAt(0);
  18.  
  19. int fillRow = scanner.nextInt();
  20. int fillCol = scanner.nextInt();
  21.  
  22. char toBeReplaced = matrix[fillRow][fillCol];
  23.  
  24. paintMatrix(matrix, toBeReplaced, fillChar, fillRow, fillCol);
  25.  
  26. for (int i = 0; i < r; i++) {
  27. for (int j = 0; j < c; j++) {
  28. System.out.print(matrix[i][j]);
  29. }
  30. System.out.println();
  31. }
  32.  
  33. }
  34.  
  35. private static void paintMatrix(char[][] matrix, char toBeReplaced, char fillChar, int fillRow, int fillCol) {
  36. if (!isInBounds(matrix, fillRow, fillCol) || matrix[fillRow][fillCol] != toBeReplaced) {
  37. return;
  38. }
  39.  
  40. matrix[fillRow][fillCol] = fillChar;
  41.  
  42. paintMatrix(matrix, toBeReplaced, fillChar, fillRow - 1, fillCol);
  43. paintMatrix(matrix, toBeReplaced, fillChar, fillRow + 1, fillCol);
  44. paintMatrix(matrix, toBeReplaced, fillChar, fillRow, fillCol - 1);
  45. paintMatrix(matrix, toBeReplaced, fillChar, fillRow, fillCol + 1);
  46.  
  47. }
  48.  
  49. private static boolean isInBounds(char[][] matrix, int fillRow, int fillCol) {
  50. return fillRow >= 0 && fillRow < matrix.length && fillCol >= 0 && fillCol < matrix[fillRow].length;
  51. }
  52.  
  53. }
Advertisement
Add Comment
Please, Sign In to add comment