Word Search(79)

本文介绍了一种使用深度优先搜索(DFS)算法解决二维网格中查找指定单词的问题。通过递归方式遍历网格,检查单词是否能按顺序由相邻字母构成,并确保同一字母单元格不被重复使用。

Word Search

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.

For example, Given board =

[ ['A','B','C','E']
['S','F','C','S'],
['A','D','E','E'] ]

word = "ABCCED", -> returns true, word = "SEE", -> returns true, word = "ABCB", -> returns false.

思路:使用dfs. 先在矩阵中找到word0],若找到,就执行helper函数继续查找。递归结束条件是 index == word.length(); 如果是超过边界或者board[i != word.charAt(index) 就return false。 为防止same letter cell may be used more than once, 要标记已经访问过的letter为 #. 每次递归结束以后还要还原以防影响下一次。

时间复杂度: mn4^(k-1). 也就是mn4^k.
m X n is board size, k is word size.
(脑补题目为从一个字符矩阵中搜索某个字符串是否存在,可以向四个方向延伸。那么dfs和bfs的时间复杂度是指数级别的,大概是4的字符串长度次方,因为每次都可能走四个方向(实际上比这个低,因为不一定四个方向都可以走,也可能走过的地方不能走,但是给出最坏情况就可以了))
空间复杂度: recuision最深是k层,recursive部分空间复杂度应该是O(k)

public class Solution {
    public boolean exist(char[][] board, String word) {
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (board[i][j] == word.charAt(0)) {
                    if (helper(i, j, 0, word,board) == true) {
                        return true;
                    }
                }
            }
            
        }
        return false;
    }
    
    private boolean helper(int i, int j, int index, String word, char[][] board) {
        if (index == word.length()) {
            return true;
        }
        if (i < 0 || j < 0 || i >= board.length || j >= board[0].length || board[i][j] != word.charAt(index)) {
            return false;
        }
        char tmp = board[i][j];
        board[i][j] = '#';
        
        boolean rst = helper(i + 1, j, index + 1, word, board) || helper(i, j + 1, index + 1, word, board) || helper(i, j - 1, index + 1, word, board) || helper(i - 1, j, index + 1, word, board);
        
        board[i][j] = tmp;
        return rst;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值