kalinikov

12. The Matrix - Stack!!!

Dec 19th, 2019
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.66 KB | None | 0 0
  1. import java.util.ArrayDeque;
  2. import java.util.Scanner;
  3.  
  4. public class TheMatrix {
  5. public static void main(String[] args) {
  6. Scanner scanner = new Scanner(System.in);
  7.  
  8. int r = scanner.nextInt();
  9. int c = scanner.nextInt();
  10. scanner.nextLine();
  11.  
  12. char[][] matrix = new char[r][c];
  13.  
  14. for (int i = 0; i < r; i++) {
  15. matrix[i] = scanner.nextLine().replaceAll(" ", "").toCharArray();
  16. }
  17.  
  18. char fillChar = scanner.nextLine().charAt(0);
  19.  
  20. int fillRow = scanner.nextInt();
  21. int fillCol = scanner.nextInt();
  22.  
  23. char toBeReplaced = matrix[fillRow][fillCol];
  24.  
  25. ArrayDeque<int[]> stack = new ArrayDeque<>();
  26.  
  27. stack.push(new int[]{fillRow, fillCol});
  28.  
  29. while (!stack.isEmpty()) {
  30. int[] indexes = stack.pop();
  31. int row = indexes[0];
  32. int col = indexes[1];
  33. matrix[row][col] = fillChar;
  34. if (isInBounds(matrix, row + 1, col) && matrix[row + 1][col] == toBeReplaced) {
  35. stack.push(new int[]{row + 1, col});
  36. }
  37. if (isInBounds(matrix, row - 1, col) && matrix[row - 1][col] == toBeReplaced) {
  38. stack.push(new int[]{row - 1, col});
  39. }
  40. if (isInBounds(matrix, row, col + 1) && matrix[row][col + 1] == toBeReplaced) {
  41. stack.push(new int[]{row, col + 1});
  42. }
  43. if (isInBounds(matrix, row, col - 1) && matrix[row][col - 1] == toBeReplaced) {
  44. stack.push(new int[]{row, col - 1});
  45. }
  46. }
  47.  
  48. //paintMatrix(matrix, toBeReplaced, fillChar, fillRow, fillCol);
  49.  
  50. for (int i = 0; i < r; i++) {
  51. for (int j = 0; j < c; j++) {
  52. System.out.print(matrix[i][j]);
  53. }
  54. System.out.println();
  55. }
  56.  
  57. }
  58.  
  59. private static void paintMatrix(char[][] matrix, char toBeReplaced, char fillChar, int fillRow, int fillCol) {
  60. if (!isInBounds(matrix, fillRow, fillCol) || matrix[fillRow][fillCol] != toBeReplaced) {
  61. return;
  62. }
  63.  
  64. matrix[fillRow][fillCol] = fillChar;
  65.  
  66. paintMatrix(matrix, toBeReplaced, fillChar, fillRow - 1, fillCol);
  67. paintMatrix(matrix, toBeReplaced, fillChar, fillRow + 1, fillCol);
  68. paintMatrix(matrix, toBeReplaced, fillChar, fillRow, fillCol - 1);
  69. paintMatrix(matrix, toBeReplaced, fillChar, fillRow, fillCol + 1);
  70.  
  71. }
  72.  
  73. private static boolean isInBounds(char[][] matrix, int fillRow, int fillCol) {
  74. return fillRow >= 0 && fillRow < matrix.length && fillCol >= 0 && fillCol < matrix[fillRow].length;
  75. }
  76.  
  77. }
Advertisement
Add Comment
Please, Sign In to add comment