每日一练_105(2021.9.21) 单词搜索(leetcode)。

本文介绍了一种使用回溯法在二维字符网格中搜索指定单词的方法。通过递归深度优先搜索,遍历网格上每个可能路径,检查是否能构成目标单词。提供了完整的Java实现代码及示例。

唉,每天也就靠看答案解析,来混混日子了。天哪,啥都不会,啥也不是......

推荐作者详解:作者:liweiwei1419
链接:https://leetcode-cn.com/problems/word-search/solution/zai-er-wei-ping-mian-shang-shi-yong-hui-su-fa-pyth/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

个人微改:

class search{
    private static final int[][] DIRECTIONS = {{-1, 0}, {0, -1}, {0, 1}, {1, 0}};
    private int rows;
    private int cols;
    private int len;
    private boolean[][] visited;
    private char[] charArray;
    private char[][] board;
    public boolean exist(char[][] board,String word) {
        this.rows = board.length;
        if(rows==0) return false;
        this.cols = board[0].length;
        this.visited = new boolean[rows][cols];
        this.len = word.length();
        this.charArray = word.toCharArray();
        this.board = board;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (dfs(i, j, 0)) {
                    return true;
                }
            }
        }
        return false;
    }
    
    public boolean inArea(int x,int y) {
        return x>=0 && x<rows && y>=0 && y<cols;
    }
    
    public boolean dfs(int x,int y,int begin) {
        if(begin == len-1) {
            return board[x][y] == charArray[begin];
        }
        if(board[x][y] == charArray[begin]) {
            visited[x][y] = true;
            for(int[] direction:DIRECTIONS) {
                int newX = x + direction[0];
                int newY = y + direction[1];
                if(inArea(newX,newY) && !visited[newX][newY]) {
                    if(dfs(newX,newY,begin+1)) {
                        return true;
                    }
                }
            }
            visited[x][y] = false;
        }
        return false;
    }
}
public class WordSearch {
    public static void main(String args[]) {
        char[][] board1 = new char[][] {{'A','B','C','D'},{'S','F','C','S'},{'A','D','E','E'}};
        String str1 = "ABCCED";
        String str2 = "ABCB";
        search hah = new search();
        System.out.println(hah.exist(board1, str1));
        System.out.println(hah.exist(board1, str2));
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

是壮壮没错了丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值