Leetcode 79单词搜索

给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false 。

单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。

思路:
简单粗暴 直接深度搜索

注意事项:
1、回溯的时候注意边界条件
2、需要用visited数组保存经过的路径,防止重复添加单词
回溯完记得将visited置为false,以免走错路径然后visited设为true

class Solution {
public:
    vector<char> path;
    bool backtracing(vector<vector<char>>& board, vector<vector<bool>>& visited, string word, int deep, int m, int n, int curm, int curn){
        if(deep == word.size()-1)
        {
            return true;
        }
        visited[curm][curn] = true;
        bool flag1 = false;
        bool flag2 = false;
        bool flag3 = false;
        bool flag4 = false;
        if(curm + 1 <= m-1 && board[curm+1][curn] == word[deep+1] && !visited[curm+1][curn])
        {
            
            flag1 = backtracing(board, visited, word, deep+1, m, n, curm+1, curn);
        }

        if(curm - 1 >= 0 && board[curm-1][curn] == word[deep+1] && !visited[curm-1][curn])
        {
            flag2 = backtracing(board, visited, word, deep+1, m, n, curm-1, curn);
        }

        if(curn + 1 <= n-1 && board[curm][curn+1] == word[deep+1] && !visited[curm][curn+1])
        {
            flag3 = backtracing(board, visited, word, deep+1, m, n, curm, curn+1);
        }

        if(curn - 1 >= 0 && board[curm][curn-1] == word[deep+1] && !visited[curm][curn-1])
        {
            flag4 = backtracing(board, visited, word, deep+1, m, n, curm, curn-1);
        }
        visited[curm][curn] = false;
        return (flag1 || flag2 || flag3 || flag4);
    }
    bool exist(vector<vector<char>>& board, string word) {
        int m = board.size();
        int n = board[0].size();
        if(word.size() > m*n)
        {
            return false;
        }
        bool checkflag = false;
        //寻找起始点
        for(int i = 0; i < m; i++)
        {
            for(int j = 0; j < n; j++)
            {
                if(board[i][j] == word[0])
                {
                    vector<vector<bool>> visited(m,vector<bool>(n, false));
                    bool flag = backtracing(board, visited, word, 0, m, n, i, j);
                    if(flag)
                    {
                        checkflag = true;
                    }
                }
            }
        }
        
        return checkflag;
    } 
};

你可能感兴趣的:(leetcode,c#,算法)