当前位置:   article > 正文

LeetCode——Word Search

LeetCode——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.

  • 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.

解法

将矩阵中的每一个字符当作起点与word做匹配,然后对其上下左右分别调用dfs,如果有满足条件的则返回true,将矩阵遍历完之后还是没有满足条件的则返回false

public boolean exist(char[][] board, String word) {
   
		if (board == null || board.length == 0)
			return false;
		int n = board.length, m = board[0].length;
		
  • 1
  • 2
  • 3
  • 4
  • 5
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/464970
推荐阅读
相关标签
  

闽ICP备14008679号