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

For example,
Given board =

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

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

DFS, 先枚举每个开始的位置,然后再用上下左右4个方向做DFS.

复制代码
class Solution {
private:
    bool canUse[100][100];
    int step[4][2];
public:
    void check(int dep, int maxDep, string &word, vector<vector<char> > &board, bool &flag, int x, int y)
    {
        if (flag)
            return;
            
        if (dep == maxDep)
        {
            flag = true;
            return;
        }
        
        for(int i = 0; i < 4; i++)
        {
            int tx = x + step[i][0];
            int ty = y + step[i][1];
            if (0 <= tx && tx < board.size() && 0 <= ty && ty < board[0].size() && canUse[tx][ty] && 
                board[tx][ty] == word[dep])
            {
                canUse[tx][ty] = false;
                check(dep + 1, maxDep, word, board, flag, tx, ty);
                canUse[tx][ty] = true;
            }
        }
    }
    
    bool exist(vector<vector<char> > &board, string word) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (word.size() == 0)
            return true;
            
        memset(canUse, true, sizeof(canUse));
            
        step[0][0] = 1;
        step[0][1] = 0;
        step[1][0] = -1;
        step[1][1] = 0;
        step[2][0] = 0;
        step[2][1] = 1;
        step[3][0] = 0;
        step[3][1] = -1;
        
        for(int x = 0; x < board.size(); x++)
            for(int y = 0; y < board[x].size(); y++)
                if (board[x][y] == word[0])
                {
                    canUse[x][y] = false;
                    bool flag = false;
                    check(1, word.size(), word, board, flag, x, y);
                    if (flag)
                        return true;
                    canUse[x][y] = true;
                }
        
        return false;
    }
};
复制代码

 

 

posted @   chkkch  阅读(2013)  评论(1编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示