Approach

This is like a backtracking problem, and we find that the size of the words is not large, so this should be the solution.

We simply just try all the permutations in words[idx:end] (handling in traverse() function). This is done by swapping idx and i (from idx to end), and then call traverse() recursively. We can swap the idx and i back after the recursive call, in this case we can reuse the words order, and don’t need extra cache for the original words value (this method is commonly used in a backtracking problem).

Notice that in the end, we need to sort the answer (I did not do this the first time and got a WA🥲).

Code

class Solution {
public:
    vector<vector<string>> wordSquares(vector<string>& words) {
        vector<string> sol;
        traverse(words, sol, 0);
        sort(ans.begin(), ans.end());
        return ans;
    }

    void traverse(vector<string>& words, vector<string>& sol, int idx) {
        if(idx == 4) {
            ans.push_back(sol);
            return;
        }
        for(int i = idx ; i < words.size() ; ++i) {
            swap(words[idx], words[i]);
            sol.push_back(words[idx]);
            // next levle
            // printSol(sol);
            if(check(sol)) traverse(words, sol, idx+1);
            // revert
            sol.pop_back();
            swap(words[idx], words[i]);
        }
    }

    bool check(const vector<string>& sol) {
        for(int i = 1 ; i < sol.size() ; ++i) {
            if(i == 1 && sol[1][0] != sol[0][0]) return false;
            if(i == 2 && sol[2][0] != sol[0][3]) return false;
            if(i == 3 && sol[3][0] != sol[1][3]) return false;
            if(i == 3 && sol[3][3] != sol[2][3]) return false;
        }
        return true;
    }

    void printSol(const vector<string>& sol) {
        for(int i = 0 ; i < sol.size() ; ++i) {
            cout << sol[i] << " ";
        }
        cout << endl;
    }

    vector<vector<string>> ans;
 };