day-24 单词搜索

在这里插入图片描述

思路:dfs思想,找到与word第一个字母相同的位置开始bfs,用id记录当前位置,如果id==word.length-1则返回true

注意:dfs的不同访问顺序可能导致结果不同,所以在每次遍历一条路径失败后,需要把相应的vis[i][j]恢复为未访问状态

code:

class Solution {
    public int[][] dir={{0,1},{0,-1},{1,0},{-1,0}};
    public int rows;
    public int cols;
    public String word;
    public boolean ans=false;
    public boolean exist(char[][] board, String word) {
        rows=board.length;
        cols=board[0].length;
        this.word=word;
        for(int i=0;i<rows;i++){
            for(int j=0;j<cols;j++){
                if(word.charAt(0)==board[i][j]){
                    boolean vis[][]=new boolean[rows][cols];
                    bfs(board,vis,i,j,0);
                }
            }
        }
        return ans;
    }
    public void bfs(char[][] board,boolean vis[][],int i,int j,int id){
        vis[i][j]=true;
        if(id==word.length()-1){
            ans=true;
            return;
        }
        for(int k=0;k<4;k++){
            int newi=i+dir[k][0];
            int newj=j+dir[k][1];
            if(0<=newi&&newi<rows&&0<=newj&&newj<cols
            &&!vis[newi][newj]&&board[newi][newj]==word.charAt(id+1)){
                bfs(board,vis,newi,newj,id+1);
                vis[newi][newj]=false;
            }
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值