Leetcode 351 Solution

This article provides solution to leetcode question 351 (android-unlock-patterns)

https://leetcode.com/problems/android-unlock-patterns

Solution

class Solution {
    int a[3][3] = {0};

public:
    int count(int y, int x, int layer, int m, int n)
    {
        if (layer > n)
            return 0;

        a[y][x] = 1;
        int res = layer >= m;

        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                if (a[i][j] == 1)
                    continue;

                if (i == y && abs(j - x) == 2 && a[i][1] == 0)
                    continue;
                else if (j == x && abs(i - y) == 2 && a[1][j] == 0)
                    continue;
                else if (abs(i - y) == 2 && abs(j - x) == 2 && a[1][1] == 0)
                    continue;

                res += count(i, j, layer + 1, m, n);
            }
        }

        a[y][x] = 0;
        return res;
    }

    int numberOfPatterns(int m, int n)
    {
        int total = 0;
        for (int i = 0; i < 3; i++)
            for (int j = 0; j < 3; j++)
                total += count(i, j, 1, m, n);
        return total;
    }
};