|
| 1 | +package com.alibaba.edison; |
| 2 | + |
| 3 | +/** |
| 4 | + * 单词搜索,medium |
| 5 | + * 给定一个m x n 二维字符网格 board 和一个字符串单词word 。如果word 存在于网格中,返回 true ;否则,返回 false 。 |
| 6 | + * 单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。 |
| 7 | + * <p> |
| 8 | + * <p> |
| 9 | + * author: qonyqian |
| 10 | + * created on: 2022/2/8 5:11 下午 |
| 11 | + * version:1.0 |
| 12 | + * description: |
| 13 | + */ |
| 14 | +public class LeetCode79 { |
| 15 | + |
| 16 | + /** |
| 17 | + * 这题好难呀,乍一看,完全没有思路 |
| 18 | + * <p> |
| 19 | + * 不过这种探索类型的题目,没想法时,用回溯法准没错 |
| 20 | + * |
| 21 | + * @param board |
| 22 | + * @param word |
| 23 | + * @return |
| 24 | + */ |
| 25 | + public boolean exist(char[][] board, String word) { |
| 26 | + int m = board.length; |
| 27 | + int n = board[0].length; |
| 28 | + boolean[][] visited = new boolean[m][n]; |
| 29 | + for (int i = 0; i < m; i++) { |
| 30 | + for (int j = 0; j < n; j++) { //以每个点为起点,依次探索 |
| 31 | + recursion(visited, m, n, i, j, board, word, 0); //递归探索 |
| 32 | + if (find) { //如果找到了,提前返回。 |
| 33 | + return true; |
| 34 | + } |
| 35 | + } |
| 36 | + } |
| 37 | + return false; |
| 38 | + } |
| 39 | + |
| 40 | + boolean find = false; |
| 41 | + |
| 42 | + /** |
| 43 | + * 递归探索单次 |
| 44 | + * |
| 45 | + * @param visited |
| 46 | + * @param m 矩阵的行 |
| 47 | + * @param n 矩阵的列 |
| 48 | + * @param x 将要探索元素的坐标 |
| 49 | + * @param y 将要探索元素的坐标 |
| 50 | + * @param board |
| 51 | + * @param word |
| 52 | + * @param index 探索 word 的第几个字符 |
| 53 | + */ |
| 54 | + public void recursion(boolean[][] visited, int m, int n, int x, int y, char[][] board, String word, int index) { |
| 55 | + if (find) { //如果已经找到了,提前返回 |
| 56 | + return; |
| 57 | + } |
| 58 | + if (index == word.length()) { //word 已经探索完,成功找到 |
| 59 | + find = true; |
| 60 | + return; |
| 61 | + } |
| 62 | + if (x < 0 || x > m - 1 || y < 0 || y > n - 1) { //元素坐标非法 |
| 63 | + return; |
| 64 | + } |
| 65 | + if (visited[x][y]) { //这个点已经探索过了,不能重复探索 |
| 66 | + return; |
| 67 | + } |
| 68 | + if (board[x][y] != word.charAt(index)) { //元素与 word 的字符不等 |
| 69 | + return; |
| 70 | + } |
| 71 | + visited[x][y] = true; //更新元素已经探索过 |
| 72 | + recursion(visited, m, n, x - 1, y, board, word, index + 1); //继续探索它的上 |
| 73 | + recursion(visited, m, n, x, y + 1, board, word, index + 1); //右 |
| 74 | + recursion(visited, m, n, x + 1, y, board, word, index + 1); //下 |
| 75 | + recursion(visited, m, n, x, y - 1, board, word, index + 1); //左 |
| 76 | + visited[x][y] = false; //回溯,恢复元素为未探索状态 |
| 77 | + } |
| 78 | +} |
0 commit comments