Offer Penalty for questions surface 12 is to prove safety --- --- 13 is backtracking



12 --- prove safety Offer- face questions backtracking

1, a matrix title path

https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof/submissions/

Backtracking

class Solution {
public:
    bool searchPath(const vector<vector<char>>& board,int i,int j,const string& word,int index,int height,int width,int len,vector<bool> searched)
    {
        if(index >= len)
            return true;
        if(i>=height || j>=width || i<0 || j<0 || board[i][j]!=word[index] || searched[j+i*width])
        {
            return false;
        }

        bool isCanGo = false;

        searched[j+i*width] = true;
        index++;
        isCanGo = searchPath(board,i+1,j,word,index,height,width,len,searched)||
                searchPath(board,i-1,j,word,index,height,width,len,searched)||
                searchPath(board,i,j+1,word,index,height,width,len,searched)||
                searchPath(board,i,j-1,word,index,height,width,len,searched);
        //不能成功的话,回溯寻找新的路径
        if(!isCanGo)
        {
            index -- ;
            searched[j+i*width] = false;
        }

        return isCanGo;
    }


    bool exist(vector<vector<char>>& board, string word)
    {
        if(board.size()==0 || word==" ")
            return false;

        int len = word.size();
        int height = board.size();
        int width = board[0].size();

        vector<bool> searched(height*width,false);

        for(int i=0; i<height; i++)
        {
            for(int j=0; j<width; j++)
            {
                if(searchPath(board,i,j,word,0,height,width,len,searched))
                    return true;
            }
        }

        return false;
    }

};

2, the range of motion of the robot 2 title

https://leetcode-cn.com/problems/ji-qi-ren-de-yun-dong-fan-wei-lcof/

Backtracking

class Solution {
public:
    int movingCount(int m, int n, int k)
    {
        if(m <= 0 || n<=0 || k < 0)
            return 0;

        vector<bool> hasGo(m*n,false);

        int result = searchPath(0,0,m,n,k,hasGo);

        return result;
    }

    int CalculateNumWei(int num1,int num2)
    {
        int result = 0;
        while(num1 != 0){
            result += num1%10;
            num1/=10;
        }
        while(num2 != 0){
            result += num2%10;
            num2/=10;
        }

        return result;
    }

    int searchPath(int i,int j,int m, int n, int k,vector<bool>& hasGo)
    {
        int count = 0;

        if(i>=m || j>=n || i<0 || j<0 || CalculateNumWei(i,j)>k ||hasGo[j+i*n])
            return count;

        hasGo[j+i*n] = true;

        count = 1 + searchPath(i+1,j,m,n,k,hasGo)+
                searchPath(i-1,j,m,n,k,hasGo)+
                searchPath(i,j+1,m,n,k,hasGo)+
                searchPath(i,j-1,m,n,k,hasGo);

        return count;
    }
};

Guess you like

Origin www.cnblogs.com/Fflyqaq/p/12444409.html