|
| 1 | +package com.onufryk.exercise; |
| 2 | + |
| 3 | +public class Question030 { |
| 4 | + private char[][] matrix = { |
| 5 | + { 'a', 'b', 'c', 'e' }, |
| 6 | + { 's', 'f', 'c', 's' }, |
| 7 | + { 'a', 'd', 'e', 'e' } }; |
| 8 | + private int rows = 3; |
| 9 | + private int cols = 4; |
| 10 | + private Boolean[][] visited = new Boolean[rows][cols]; |
| 11 | + private int pathLength = 0; |
| 12 | + |
| 13 | + public Boolean containsPath(String str) { |
| 14 | + if (this.matrix == null || this.rows < 1 || this.cols < 1 || str == null) { |
| 15 | + return false; |
| 16 | + } |
| 17 | + this.pathLength = 0; |
| 18 | + for (int row = 0; row < this.rows; row++) { |
| 19 | + for (int col = 0; col < this.cols; col++) { |
| 20 | + this.visited[row][col] = false; |
| 21 | + } |
| 22 | + } |
| 23 | + for (int row = 0; row < this.rows; row++) { |
| 24 | + for (int col = 0; col < this.cols; col++) { |
| 25 | + if (this.containsPath(str, row, col)) { |
| 26 | + return true; |
| 27 | + } |
| 28 | + } |
| 29 | + } |
| 30 | + return false; |
| 31 | + } |
| 32 | + |
| 33 | + private Boolean containsPath(String str, int row, int col) { |
| 34 | + if (this.pathLength == str.length()) { |
| 35 | + return true; |
| 36 | + } |
| 37 | + Boolean hasPath = false; |
| 38 | + |
| 39 | + if (row >= 0 && row < this.rows && col >= 0 && col < this.cols |
| 40 | + && this.matrix[row][col] == str.charAt(this.pathLength) && !this.visited[row][col]) { |
| 41 | + this.pathLength++; |
| 42 | + this.visited[row][col] = true; |
| 43 | + hasPath = this.containsPath(str, row, col - 1) || this.containsPath(str, row - 1, col) |
| 44 | + || this.containsPath(str, row, col + 1) || this.containsPath(str, row + 1, col); |
| 45 | + if (!hasPath) { |
| 46 | + this.pathLength--; |
| 47 | + this.visited[row][col] = false; |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + return hasPath; |
| 52 | + } |
| 53 | + |
| 54 | + public static void main(String[] args) { |
| 55 | + Question030 app = new Question030(); |
| 56 | + System.out.println(app.containsPath("bcced")); |
| 57 | + System.out.println(app.containsPath("abcb")); |
| 58 | + System.out.println(app.containsPath("abceseedasfc")); |
| 59 | + } |
| 60 | + |
| 61 | +} |
0 commit comments