[LeetCode] 79. Word Search

题:https://leetcode.com/problems/word-search/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.

题目大意

在矩阵中寻找字符串,字符串的相邻字符在矩阵上都相邻 且 矩阵上的字符只能用一次。

思路

组合问题 考虑 BDFS 。

判断问题 作为 递归
递归函数boolean bdfs(board,word,wordLen,curp,r,c ):以r,c为起点 word是否在矩阵中。

递归函数转移方程:bdfs(board,word,wordLen,curp,r,c )= any( bdfs(board,word,wordLen,curp+1,nr,nc )) ,在矩阵当前位置 元素 可作为 word的 当前 字符的情况下,以矩阵当前位置的周围位置为起点 剩余word字串是否在 矩阵中。

终止条件:

  1. 若word为空,用curp 访问的点为 word 越界表示。返回 true。
  2. 矩阵当前位置 元素 不 可作为 word的 当前 字符,返回false。
class Solution {
    boolean[][] isVisited;
    int m,n;
    int[][] directions = {{-1,0},{1,0},{0,-1},{0,1}};

    public boolean bdfs(char[][] board, String word,int wordLen,int curp,int r,int c){
        if(wordLen == curp)
            return true;
        if(!( r>=0 && r< board.length && c >= 0 && c< board[0].length) || isVisited[r][c] == true || word.charAt(curp) != board[r][c])
            return false;
            
        isVisited[r][c] = true;
        for(int[] direction:directions) {
            int nr = r + direction[0];
            int nc = c + direction[1];
            if(bdfs(board,word,wordLen,curp+1,nr,nc))
                return true;
        }
        isVisited[r][c] = false;
        return false;
    }
    public boolean exist(char[][] board, String word) {
        isVisited = 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(bdfs(board,word,word.length(),0,i,j))
                    return true;
        return false;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值