79. Word Search (M)

Word Search (M)

Given a 2D board and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where “adjacent” cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

Example:

board =
[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.

题意

判断给定矩阵中是否存在一组相邻字符序列,能够组成目标字符串。即以矩阵中一字符为起点,只能上下左右走且不能重复访问元素,判断有无这样一条路径,使起点到终点的字符序列正好组成目标字符串。

思路

回溯法。


代码实现

class Solution {
    // 控制左上右下四个方向坐标的变化
    private int[] iPlus = {0, -1, 0, 1};
    private int[] jPlus = {-1, 0, 1, 0};
    private int m, n;

    public boolean exist(char[][] board, String word) {
        m = board.length;
        n = board[0].length;
        boolean[][] visited = new boolean[m][n];

        // 先找到与第一个字符相同的位置,以该位置为起点搜索路径
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (board[i][j] == word.charAt(0)) {
                    visited[i][j] = true;
                    if (search(board, i, j, word, 0, visited)) {
                        return true;
                    }
                    visited[i][j] = false;
                }
            }
        }
        
        return false;
    }

    private boolean search(char[][] board, int i, int j, String word, int index, boolean[][] visited) {
        if (index == word.length() - 1) {
            return true;
        }

        for (int x = 0; x < 4; x++) {
            int nextI = i + iPlus[x];
            int nextJ = j + jPlus[x];

            // 判断邻接点是否在矩阵内
            if (nextI < 0 || nextI >= m || nextJ < 0 || nextJ >= n) {
                continue;
            }

            // 如果邻接点与字符串中下一个字符匹配,且尚未被访问,则继续递归搜索
            if (!visited[nextI][nextJ] && board[nextI][nextJ] == word.charAt(index + 1)) {
                visited[nextI][nextJ] = true;
                if (search(board, nextI, nextJ, word, index + 1, visited)) {
                    return true;
                }
                visited[nextI][nextJ] = false;
            }
        }
        
        return false;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值