[Sword Finger 12] The path in the matrix

Method 1: Simulate the traversal matrix: time O( 3 k 3^{k}3k mn), space O(mn)

k: string length, m, n: matrix length and width

Time complexity: each position has three directions to go (can't go back), so the time is 3 k 3^{k}3k . Each position of the matrix should be checked for correctness, so the time m*n
problem solution:

  1. Traverse the entire matrix, if the conditions are met, simulate walking up, down, left, and right to see if there is a path to meet
  2. You can’t go back, so mark the path you walked on the board every time, and you should restore the last state when you backtrack.
  3. Pay attention to the end condition
class Solution {
    
    
public:
    bool Ritway(vector<vector<char>>& board, string& word, int i, int j, int index)
    {
    
    
        if (i < 0 || i == board.size() || j < 0 || j == board[0].size() || board[i][j] != word[index])
            return false;
        if (index == word.size() - 1)
            return true;
        // 关键就是这里设置已经走过的路径!!不需要新建一个board保存走过的路径,在原始棋盘上更改就行了
        board[i][j] = '\0';
        // 判断上下左右是否有正确路径
        bool flag = Ritway(board, word, i - 1, j, index + 1) ||
                    Ritway(board, word, i + 1, j, index + 1) ||
                    Ritway(board, word, i, j - 1, index + 1) ||
                    Ritway(board, word, i, j + 1, index + 1);
        // 在检测完该条路径之后,应该恢复原始棋盘的样子
        board[i][j] = word[index];
        return flag;
    }
    bool exist(vector<vector<char>>& board, string word) 
    {
    
    
        if (word.size() == 0)
            return false;
        for (int i = 0; i < board.size(); i++)
        {
    
    
            for (int j = 0; j < board[0].size(); j++)
            {
    
    
                if (Ritway(board, word, i, j, 0))
                {
    
    
                    return true;
                }
            }
        }
        return false;
    }
};

Guess you like

Origin blog.csdn.net/qq_45691748/article/details/112478049