package swordOffre.gaopengyu; import java.awt.*; public class PathInMatrix12 { public static void main(String[] args) { char[] matrix = new char[]{'a', 'b', 't', 'g', 'c', 'f', 'c', 'g', 'j', 'd', 'e', 'h'}; int rows = 3, cols = 4; String str = "bfce"; boolean isHasPath = hasPath(matrix, rows, cols, str); if (isHasPath) { System.out.println("Yeah!"); } else { System.out.println("Oh,no~"); } } public static boolean hasPath(char[] matrix, int rows, int cols, String str) { if (matrix == null || rows < 1 || cols < 1 || str.length() < 1) { return false; } boolean result = false; boolean[] visited = new boolean[rows * cols]; for (int i = 0; i < rows * cols; i++) { visited[i] = false; } A: for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { result = isHasPathCore(matrix, rows, cols, str, i, j, visited, 0); if (result) { break A; } } } return result; } public static boolean isHasPathCore(char[] matrix, int rows, int cols, String str, int row, int col, boolean[] visited, int stri) { if (stri == str.length()) { return true; } if (0 > row || row >= matrix.length || 0 > col || col >= matrix.length) { return false; } boolean result = false; if (str.charAt(stri) == matrix[row * cols + col] && !visited[row * cols + col]) { visited[row * cols + col] = true; stri++; if (isHasPathCore(matrix, rows, cols, str, row - 1, col, visited, stri) || isHasPathCore(matrix, rows, cols, str, row, col - 1, visited, stri) || isHasPathCore(matrix, rows, cols, str, row + 1, col, visited, stri) || isHasPathCore(matrix, rows, cols, str, row, col + 1, visited, stri)) { result = true; } else { visited[row * cols + col] = false; } } return result; } }
矩阵中的路径12
最新推荐文章于 2024-01-10 07:00:00 发布