每日一题算法:2020年9月13日 [单词搜索](https://leetcode-cn.com/problems/word-search/) exist

2020年9月13日 单词搜索 exist

在这里插入图片描述

class Solution {
    public boolean exist(char[][] board, String word) {

    }
}

解题思路:

首先遍历数组,找到一个对应的起始节点,也就是和word的首字母相同的坐标位置。

然后以这个位置作为起点,对其进行递归处理,这个递归的函数另外写一个,然后返回该点的递归结果。

递归的规则:

当前点是否是字符串的index坐标的字符时,判断index是否是字符串的长度,如果不是,那就判断周围四个是否是目标字符,或者是已经判断过的坐标。

由于字符是不允许重复使用的,那么怎么确定被使用过呢?那就把board复制一个空的出来,在主函数中遍历的时候,找到一个字符相等的就把他清空一遍。这样,在递归过程中就不会出现重复使用,递归结束后清空,这样不会影响下一个递归。

发现错误:进过分析,发现是递归的过程中没有考虑到状态状态的回溯,需要增加一个回溯的功能。
在这里插入图片描述

    int[][] map;
    char[][] board;
    int width;
    int height;
    int len;
    String word;

    public boolean exist(char[][] board, String word) {

        len=word.length();
        width=board.length;
        height=board[0].length;
        this.word=word;
        this.board=board;

        for (int i=0;i<width;i++){
            for (int j=0;j<height;j++){

                map=new int[width][height];

                if(tryExist(i,j,0))
                {
                    return true;
                }
            }
        }
        return false;
    }
    //递归函数
    public boolean tryExist(int x,int y,int index){



        if (map[x][y]==1)
            return false;


        //如果当前位置相等
        if (board[x][y]==word.charAt(index)){

            //标记位置
            map[x][y]=1;

            if (index==len-1)
                return true;

            //递归周围四个
            if (x+1<width) {
                //如果这一个位置存在,递归他
                if (tryExist(x+1,y ,index+1)){
                    return true;
                }
            }
            if (x-1>-1){
                if (tryExist(x-1,y ,index+1)){
                    return true;
                }
            }
            if (y-1>-1){
                if (tryExist(x,y-1 ,index+1)){
                    return true;
                }
            }
            if (y+1<height){
                if (tryExist(x,y+1 ,index+1)){
                    return true;
                }
            }
        }

        return false;

    }

二维数组的递归回溯需要复制数组,数组复制有些麻烦。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值