Word Search --DFS

0x01. Issues

Given a two-dimensional grid and a word, to find out whether the word exists in the grid.
Words must, by the letters in adjacent cells constituting alphabetically, where "adjacent" cells that are adjacent horizontally or vertically adjacent cells. Letters within the same cell is not allowed to be reused.
Input Example:
Board =
[
[ 'A', 'B', 'C', 'E'],
[ 'S', 'F.', 'C', 'S'],
[ 'A', 'D' , 'E', 'E']
]
given word = "ABCCED", returns true
given word = "SEE", returns true
given word = "ABCB", return false
tips: boardand wordcontains only uppercase and lowercase English letter.1 <= board.length <= 200 1 <= board[i].length <= 200 1 <= word.length <= 10^3

0x02. Analysis

Search for words in a two-dimensional matrix, without a doubt, the use of search, which DFS would be better.

But we still have some considerations:

  • Note that each condition returned.
  • Note the word under the control of the subject.
  • Note tag has access to the elements.
  • This problem will be more convenient to consider the recursion.

optimization:

  • Using arguments passed.
  • Use a tempvariable optimized away memorandum array.

0x03. Resolution code -DFS (recursive)

class Solution {
public:
    int dir[4][4]={{-1,0},{1,0},{0,-1},{0,1}};
    bool dfs(vector<vector<char>>& board,string& word,int i,int j,int w){
        if(board[i][j]!=word[w]) return false;
        if(w==word.size()-1) return true;
        char temp=board[i][j];
        board[i][j]='0';
        for(int k=0;k<4;k++){
            int new_x=i+dir[k][0];
            int new_y=j+dir[k][1];
            if(new_x>=0&&new_x<board.size()&&new_y>=0&&new_y<board[0].size()){
                if(dfs(board,word,new_x,new_y,w+1)) return true;
            }
        }
        board[i][j]=temp;
        return false;
    }
    bool exist(vector<vector<char>>& board, string word) {
        for(int i=0;i<board.size();i++){
            for(int j=0;j<board[i].size();j++){
                if(board[i][j]==word[0]){
                    if(dfs(board,word,i,j,0)) return true;
                }
            }
        }
        return false;
    }
};

ATFWUS  --Writing  By 2020–03–21

Published 128 original articles · won praise 144 · views 10000 +

Guess you like

Origin blog.csdn.net/ATFWUS/article/details/105008568