79. Word Search LeetCode

来源:互联网 发布:天干地支日期互算法 编辑:程序博客网 时间:2024/04/30 18:52

题意:给一个存有字母的二维矩阵和一个单词,问单词是否可以是二维矩阵的一条路径上的字母组成的,路径移动方向是4个方向,上下左右。
题解:dfs即可。

class Solution {public:    int dir[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};    bool dfs(vector<vector<char>>& board, string word,int i,int j)    {        if(word.length() < 1) return true;        char c = board[i][j];        int n = board.size();        int m = board[0].size();        board[i][j] = '\0';        bool flag = false;        for(int k = 0; k < 4; k++)        {            int tx = i + dir[k][0];            int ty = j + dir[k][1];            if(tx < 0 || ty < 0 || tx >= n || ty >= m || board[tx][ty] != word[0]) continue;            flag |= dfs(board,word.substr(1),tx,ty);        }        if(flag) return true;        board[i][j] = c;        return false;    }    bool exist(vector<vector<char>>& board, string word) {        int n = board.size();        int m = board[0].size();        for(int i = 0; i < n; i++)            for(int j = 0; j < m; j++)                if(board[i][j] == word[0] && dfs(board,word.substr(1),i,j))                    return true;        return false;    }};
0 0
原创粉丝点击