LeetCode 79. Word Search

来源:互联网 发布:高考语文 知乎 编辑:程序博客网 时间:2024/06/15 03:54

79. 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 =

[  ['A','B','C','E'],  ['S','F','C','S'],  ['A','D','E','E']]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

/*题意:给定一个由字母组成的二维地图和一个单词,判断单词是否能够由地图中的相邻(水平或垂直)字母组成相同位置的字母只能使用一次*/class Solution {public:    int dir[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};//四个方向    int dfs(vector<vector<char>>& board, string word, int x, int y, int m, int n, int pos) {        //用来在2D地图中搜索和word匹配的路径        if(board[x][y] == '\0' || board[x][y] != word[pos])            return 0;        if(pos+1 == word.length())            return 1;        char c = board[x][y];        for(int i = 0; i < 4; i++){            int cur_x = x + dir[i][0];            int cur_y = y + dir[i][1];            if(cur_x >= 0 && cur_x < m && cur_y >= 0 && cur_y < n) {                board[x][y] = '\0';//标记该位置已经查找过                if(dfs(board, word, cur_x, cur_y, m, n, pos+1)) {                    return 1;                }                board[x][y] = c;//搜索不成功取消该位置的标记            }        }        return 0;    }    bool exist(vector<vector<char>>& board, string word) {        int m = board.size();        int n = board[0].size();        for(int i = 0; i < m; i++){//从地图的每个位置开始尝试搜索该单词是否存在            for(int j = 0; j < n; j++){                if(dfs(board, word, i, j, m, n, 0))                    return true;            }        }        return false;    }};


原创粉丝点击