C++ backtracking using visited and skip array (beating 93.1% using 9ms)


  • 0
    M

    A revised version based on @chenhaoze94's solution

    class Solution {
    public:
        int dfs(vector<bool>& visited, vector<vector<int>>& skip, int cur, int idx, int m, int n){
            if(idx == n) return 1;
            int res = 0;
            
            visited[cur] = true;        
            for(int i = 1; i <= 9; ++i){
                if(!visited[i] && (!skip[cur][i] || visited[skip[cur][i]]))
                    res += dfs(visited, skip, i, idx + 1, m, n);
            }
            visited[cur] = false;
            return res + (idx >= m ? 1 : 0);
        }
    
        int numberOfPatterns(int m, int n) {       
            vector<vector<int>>skip(10, vector<int>(10));
            skip[1][3] = skip[3][1] = 2, skip[1][7] = skip[7][1] = 4;
            skip[3][9] = skip[9][3] = 6, skip[7][9] = skip[9][7] = 8;
            skip[1][9] = skip[9][1] = skip[3][7] = skip[7][3] = skip[2][8] = skip[8][2] = skip[4][6] = skip[6][4] = 5;
            
            vector<bool> visited(10, false);
            int res = 0;
            res += dfs(visited, skip, 1, 1, m, n) * 4;
            res += dfs(visited, skip, 2, 1, m, n) * 4;
            res += dfs(visited, skip, 5, 1, m, n);
            return res;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.