79. Word Search

本文介绍了一种使用深度优先搜索(DFS)算法在字符的二维数组中查找特定单词的方法。通过迭代地从每个位置开始进行DFS,如果单词长度为0则返回真,如果数组为空则返回假。在DFS过程中,检查边界条件,标记已访问的单元格,并在四个方向上递归调用DFS。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

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.
Problem URL


Solution

给一个字符的二维数组,搜索数组中是否存在给定的单词。

We could simply run a dfs to solve this problem. If word is with length 0, return true; If board is empty, return false. Then iteratively start dfs in each position.

In dfs, if out of bound or visited or word is different, retrun false, if match, return true. Set visited to true and count ++. Then recursively call dfs in four direction, remember reset visited to false for backtracking.

Code
class Solution {
    private int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; 
    public boolean exist(char[][] board, String word) {
        if (word.length() == 0){
            return true;
        }
        if (board.length == 0 || board[0].length == 0){
            return false;
        }
        boolean[][] visited = new boolean[board.length][board[0].length];
        for (int i = 0; i < board.length; i++){
            for (int j = 0; j < board[0].length; j++){
                if (dfs(board, word, i, j , 0, visited)){
                    return true;
                }
            }
        }
        return false;
    }
    
    private boolean dfs(char[][] board, String word, int i, int j, int count, boolean[][] visited){
        if (i < 0 || j < 0 || i >= board.length || j >= board[0].length || visited[i][j] || board[i][j] != word.charAt(count)){
            return false;
        }
        if (count == word.length() - 1){
            return true;
        }
        visited[i][j] = true;
        count++;
        for (int[] dir : dirs){
            int x = i + dir[0];
            int y = j + dir[1];
            if (dfs(board, word, x, y, count, visited)){
                return true;
            }
        }
        visited[i][j] = false;
        return false;
    }
}

Time Complexity: O()
Space Complexity: O()


Review
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值