|
| 1 | +package BackTracking; |
| 2 | + |
| 3 | +/** |
| 4 | + * Created by 周杰伦 on 2018/7/20. |
| 5 | + */ |
| 6 | +public class 脑洞大开的矩阵查找单词 { |
| 7 | + |
| 8 | + static class StopMsgException extends RuntimeException { |
| 9 | + |
| 10 | + } |
| 11 | + |
| 12 | + static boolean flag; |
| 13 | + |
| 14 | + public boolean exist(char[][] board, String word) { |
| 15 | + if (word.equals("")) { |
| 16 | + return true; |
| 17 | + } |
| 18 | + int[][] visit = new int[board.length][board[0].length]; |
| 19 | + flag = false; |
| 20 | + try { |
| 21 | + for (int i = 0; i < board.length; i++) { |
| 22 | + for (int j = 0; j < board[0].length; j++) { |
| 23 | + if (word.charAt(0) == board[i][j]) { |
| 24 | + dfs(board, word, visit, i, j); |
| 25 | + } |
| 26 | + } |
| 27 | + } |
| 28 | + } catch (StopMsgException e) { |
| 29 | + System.out.println(e); |
| 30 | + } |
| 31 | + return flag; |
| 32 | + } |
| 33 | + |
| 34 | + public void dfs(char[][] board, String word, int[][] visit, int i, int j) { |
| 35 | + if (word.equals("")) { |
| 36 | + flag = true; |
| 37 | + throw new StopMsgException(); |
| 38 | + } |
| 39 | + if (i > board.length - 1 || i < 0 || j > board[0].length - 1 || j < 0) { |
| 40 | + return; |
| 41 | + } |
| 42 | + if (visit[i][j] == 1) { |
| 43 | + return; |
| 44 | + } |
| 45 | + |
| 46 | + if (word.charAt(0) == board[i][j]) { |
| 47 | + visit[i][j] = 1; |
| 48 | + dfs(board, word.length() == 1 ? "" : word.substring(1, word.length()), visit, i + 1, j); |
| 49 | + dfs(board, word.length() == 1 ? "" : word.substring(1, word.length()), visit, i - 1, j); |
| 50 | + dfs(board, word.length() == 1 ? "" : word.substring(1, word.length()), visit, i, j - 1); |
| 51 | + dfs(board, word.length() == 1 ? "" : word.substring(1, word.length()), visit, i, j + 1); |
| 52 | + visit[i][j] = 0; |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | +} |
0 commit comments