LeetCode-Word Search

本文介绍如何使用深度优先搜索算法解决二维矩阵中寻找指定单词的问题。算法通过标记已访问的字符,确保不重复使用同一位置,最终判断单词是否存在于矩阵中。

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

<a target=_blank href="https://oj.leetcode.com/problems/word-search/">
</a>
https://oj.leetcode.com/problems/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 =

[
  ["ABCE"],
  ["SFCS"],
  ["ADEE"]
]

word = "ABCCED", -> returns true,

word = "SEE", -> returns true,

word = "ABCB", -> returns false.

这题是深度优先搜索,但是在进入下一步之前会把当前格标记为‘.’,避免重复使用。

一次搜索的复杂度是O(E+V),E是边的数量,V是顶点数量,在这个问题中他们都是O(m*n)量级的(因为一个顶点有固定上下左右四条边)。加上我们对每个顶点都要做一次搜索,所以总的时间复杂度最坏是O(m^2*n^2)

空间复杂度是递归过程中产生的,大约是O(4*word.length())


public class Solution {  
   public boolean exist(char[][] board, String word) {  
     if(word==null || word.length()==0) return true;  
     if(board==null || board.length==0) return false;  
     for(int i=0; i<board.length; i++){  
       for(int j=0; j<board[0].length; j++){  
         boolean ret = helper(board, word, 0, i, j);  
         if(ret==true) return true;  
       }  
     }  
     return false;  
   }  
   public boolean helper(char[][]board, String word, int index, int x, int y){  
     if(index==word.length()) return true;  
     if(x<0||x>=board.length||y<0||y>=board[0].length||board[x][y]!=word.charAt(index)) return false;  
     char c = board[x][y];  
     board[x][y] = '.';  
     boolean ret = helper(board, word, index+1, x-1, y)||  
             helper(board, word, index+1, x+1, y)||  
             helper(board, word, index+1, x, y-1)||  
             helper(board, word, index+1, x, y+1);  
     board[x][y] = c;  
     return ret;  
   }  
 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值