LintCode 123 · Word Search (DFS字符处理经典题!)

123 · Word Search

Algorithms

Medium

Description

Given a 2D board and a string word, find if the string word exists in the grid.

The string 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.

The dimension of the letter matrix does not exceed 100, and the length of the string does not exceed 100.

Example

Example 1:

Input:

board = ["ABCE","SFCS","ADEE"]

word = "ABCCED"

Output:

true

Explanation:

[

A B C E

S F C S

A D E E

]

(0,0)->(0,1)->(0,2)->(1,2)->(2,2)->(2,1)

Example 1:

Input:

board = ["z"]

word = "z"

Output:

true

Explanation:

[ z ]

(0,0)

解法1:DFS+hashset。

很多小地方需要注意,特别是visited[][]数组什么时候clear掉。

cpp 复制代码
class Solution {
public:
    /**
     * @param board: A list of lists of character
     * @param word: A string
     * @return: A boolean
     */
    bool exist(vector<vector<char>> &board, string &word) {
        int m = board.size();
        if (m == 0) return word.empty();
        int n = board[0].size();
        string sol = "";
        for (int i = 0; i < word.size(); i++) {
            string tmpStr = word.substr(0, i + 1);
            s.insert(tmpStr);
        }
        vector<vector<bool>> visited;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                sol.clear(); //这里每次都要clear!不然后面的操作就append到s上面!
                visited.resize(m, vector<bool>(n, false));
                sol += board[i][j];
                if (check(board, word, sol, visited, i, j)) return true;
            }
        }
        return false;
    }
private:
    int dx[4] = {0, 0, 1, -1};
    int dy[4] = {1, -1, 0, 0};
    set<string> s;
    bool check(vector<vector<char>> &board, string &word, string sol, vector<vector<bool>> &visited, int x, int y) {
        if (s.find(sol) == s.end()) return false;
        if (sol == word) {
            return true;
        }
        if (sol.size() >= word.size()) return false;
        visited[x][y] = true;
        for (int i = 0; i < 4; i++) {
            int newX = x + dx[i];
            int newY = y + dy[i];
            if (newX >= 0 && newX < board.size() && newY >= 0 && newY < board[0].size() && !visited[newX][newY]) {
                sol += board[newX][newY];
                if (check(board, word, sol, visited, newX, newY)) return true;
                else sol.pop_back();  //这一行重要!因为sol还要被for循环的其它i用到!
            }
        }
        visited[x][y] = false; //这一行重要,只有当dfs能够一直往下进行,visited[][]才不用动,否则如果dfs中途退出,visited[][]要clear。不然就跟后面操作冲突!
        return false; //这里别忘了,不然默认可能会返回true!!!
    }
};

二刷:不需要set。每次比较当前位置的字符就可以了。

cpp 复制代码
class Solution {
public:
    /**
     * @param board: A list of lists of character
     * @param word: A string
     * @return: A boolean
     */
    bool exist(vector<vector<char>> &board, string &word) {
        int m = board.size();
        if (m == 0) return word.empty();
        int n = board[0].size();
        string sol = "";
        vector<vector<bool>> visited;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                sol.clear();
                visited.resize(m, vector<bool>(n, false));
                sol += board[i][j];
                if (check(board, word, sol, 0, visited, i, j)) return true;
            }
        }
        return false;
    }
private:
    int dx[4] = {0, 0, 1, -1};
    int dy[4] = {1, -1, 0, 0};
    bool check(vector<vector<char>> &board, string &word, string sol, int pos, vector<vector<bool>> &visited, int x, int y) {
        if (sol[pos] != word[pos]) return false;
        if (sol == word) {
            return true;
        }
        //if (sol.size() >= word.size()) return false; //这一行不需要!如果不匹配早就返回了,匹配上面也会返回true。
        visited[x][y] = true;
        for (int i = 0; i < 4; i++) {
            int newX = x + dx[i];
            int newY = y + dy[i];
            if (newX >= 0 && newX < board.size() && newY >= 0 && newY < board[0].size() && !visited[newX][newY]) {
                sol += board[newX][newY];
                if (check(board, word, sol, pos + 1, visited, newX, newY)) return true;
                else sol.pop_back();  //这一行重要!因为sol还要被for循环的其它i用到!
            }
        }
        visited[x][y] = false; //这一行重要,只有当dfs能够一直往下进行,visited[][]才不用动,否则如果dfs中途退出,visited[][]要clear。不然就跟后面操作冲突!
        return false;
    }
};

三刷: DFS+Trie

TBD

四刷:BFS

TBD

相关推荐
LluckyYH13 小时前
代码随想录Day 58|拓扑排序、dijkstra算法精讲,题目:软件构建、参加科学大会
算法·深度优先·动态规划·软件构建·图论·dfs
新手unity自用笔记14 小时前
项目-坦克大战学习-子弹的移动与销毁
笔记·学习·c#
qinzechen15 小时前
分享几个做题网站------学习网------工具网;
java·c语言·c++·python·c#
yufei-coder18 小时前
C# Windows 窗体开发基础
vscode·microsoft·c#·visual studio
dangoxiba19 小时前
[Unity Demo]从零开始制作空洞骑士Hollow Knight第十三集:制作小骑士的接触地刺复活机制以及完善地图的可交互对象
游戏·unity·visualstudio·c#·游戏引擎
AitTech19 小时前
深入理解C#中的TimeSpan结构体:创建、访问、计算与格式化
开发语言·数据库·c#
hiyo5851 天前
C#中虚函数和抽象函数的概念
开发语言·c#
开心工作室_kaic1 天前
基于微信小程序的校园失物招领系统的设计与实现(论文+源码)_kaic
c语言·javascript·数据库·vue.js·c#·旅游·actionscript
叫我Cow_1 天前
全排列和组合数区分
算法·深度优先·图论
时光追逐者1 天前
WaterCloud:一套基于.NET 8.0 + LayUI的快速开发框架,完全开源免费!
前端·microsoft·开源·c#·.net·layui·.netcore