Leetcode Word search

本文介绍了一个二维网格中查找特定单词的算法实现。采用深度优先搜索(DFS)策略,递归地从每个可能的起点开始搜索目标单词,确保不重复使用同一字母。通过标记已访问节点避免重复访问。

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,

[
  ["ABCE"],
  ["SFCS"],
  ["ADEE"]
]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

[code]

public class Solution {
    public boolean exist(char[][] board, String word) {
        if(word==null || word.equals(""))return true;
        if(board==null || board.length==0 || board[0].length==0)return false;
        int m=board.length, n=board[0].length;
        char [] cs=word.toCharArray();
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                if(board[i][j]==cs[0])
                {
                    if(dfs(i,j,board,0,cs))return true;
                }
            }
        }
        return false;
    }

    boolean dfs(int row, int col, char[][]board, int index, char[]cs)
    {
        if(index==cs.length)return true;
        if(row<0 || row>=board.length || col<0 || col>=board[0].length || board[row][col]=='.')return false;

        if(board[row][col]==cs[index])
        {
            board[row][col]='.';
            if(dfs(row+1, col, board, index+1, cs))return true;
            if(dfs(row-1, col, board, index+1, cs))return true;
            if(dfs(row,col+1, board, index+1, cs))return true;
            if(dfs(row, col-1, board, index+1, cs))return true;
            board[row][col]=cs[index];
        }
        return false;
    }
}

[Thoughts]
dfs, bfs 都不要忘了mark visited过的nodes

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值