单词搜索记录

题目要求

给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false 。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
在这里插入图片描述

思路:

  • 从board的(0,0)位置出发,依次向上向下向左向右遍历,看遍历到的元素是否和word相应的位置元素相等,在此过程中记录表示word下标的指针index,若index >= word.length(),则说明找到了一条路径。
  • 同时,由于题目中要求 同一个单元格内的字母不允许被重复使用 所以使用和board等大小的visited数组标识,从当前位置出发访问过board的元素相应的在visited中设置为true。
  • (但是在递归的过程中需要恢复现场,因为假设在(0,0)位置开始查找时visited[0][0] 设置为true,表示已经被访问过,但是再从board中(0,1)位置开始时,(0,0)应该是没有被访问过的状态。)
public class WordSearch {

    public boolean exist(char[][] board, String word) {
        int N = board.length;
        int M = board[0].length;
        char[] words = word.toCharArray();
        boolean[][] visited = new boolean[N][M];    // 记录在当前递归中该元素是否被访问过
        // 需要从board中的每个字符中尝试
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < M; j++) {
                boolean res = process(board,words,visited,i,j,0);
                if (res) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean process(char[][] board, char[] words, boolean[][] visited, int curX, int curY, int index) {
        if (index >= words.length) {
            return true;
        }
        // 剪枝
        if (curX < 0 || curY < 0 || curX >= board.length || curY >= board[0].length || board[curX][curY] != words[index] || visited[curX][curY] == true) {
            return false;
        }
        visited[curX][curY] = true;
        boolean res = process(board, words, visited, curX + 1, curY,index + 1) ||
                process(board, words, visited,curX - 1,curY,index + 1) ||
                process(board, words, visited, curX,curY - 1, index + 1) ||
                process(board, words, visited, curX, curY + 1, index + 1);
        visited[curX][curY] = false;    // 恢复现场
        return res;

    }

}

最后提交结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值