AB Graph (Codeforces 1481D)
Tags: Greedy, graphs

Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem.  You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m > 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times.

Input: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases.The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome.Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$.Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops.It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$.

Output: For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them.Otherwise, (if there is no answer) print "NO".

Note: The graph from the first three test cases is shown below:  In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba.

Sample Inputs:
5
3 1
*ba
b*b
ab*
3 3
*ba
b*b
ab*
3 4
*ba
b*b
ab*
4 6
*aaa
b*ba
ab*a
bba*
2 6
*a
b*

Sample Outputs:
YES
1 2
YES
2 1 3 2
YES
1 3 1 3 1
YES
1 2 1 3 4 1 4
NO

Solution (Python):
def alternating(vals, m):
    ans = []
    for i in range(m):
        ans.append(vals[i % len(vals)])
    return ans

def solve(n, m, mat):
    if mat[0][1] == mat[1][0]:
        print('YES')
        print(' '.join(alternating(['1', '2'], m + 1)))
    elif m & 1 == 1:
        print('YES')
        print(' '.join(alternating(['1', '2'], m + 1)))
    elif n == 2:
        print('NO')
    elif mat[1][2] == mat[2][1]:
        print('YES')
        print(' '.join(alternating(['2', '3'], m + 1)))
    elif mat[0][2] == mat[2][0]:
        print('YES')
        print(' '.join(alternating(['1', '3'], m + 1)))
    elif mat[0][1] == mat[1][2] == mat[2][0]:
        print('YES')
        print(' '.join(alternating(['1', '2', '3'], m + 1)))
    elif mat[0][1] == mat[2][1] == mat[1][0]:
        print('YES')
        print(' '.join(alternating(['1', '3', '2'], m + 1)))
    else:
        if mat[0][1] != mat[0][2]:
            (center, neigh) = ('1', ['2', '3'])
        elif mat[1][0] != mat[1][2]:
            (center, neigh) = ('2', ['1', '3'])
        else:
            (center, neigh) = ('3', ['1', '2'])
        ans = []
        if m // 2 & 1 == 0:
            ans += alternating([center, neigh[0]], m // 2 + 1)
            ans += alternating([neigh[1], center], m // 2)
        else:
            ans += alternating([neigh[0], center], m // 2 + 1)
            ans += alternating([neigh[1], center], m // 2)
        print('YES')
        print(' '.join(ans))
if __name__ == '__main__':
    T = int(input())
    for t in range(T):
        (n, m) = tuple(map(int, input().split()))
        mat = [input() for _ in range(n)]
        solve(n, m, mat)

Solution (Python):
from itertools import permutations

def solution(n, m, mat):
    sol = []
    if m % 2 == 1:
        print('YES')
        for i in range(m + 1):
            sol.append(i % 2 + 1)
        print(*sol)
        return
    elif n == 2 and mat[0][1] != mat[1][0]:
        print('NO')
        return
    elif n == 2:
        print('YES')
        for i in range(m + 1):
            sol.append(i % 2 + 1)
        print(*sol)
        return
    else:
        for [u, v] in [[0, 1], [0, 2], [1, 2]]:
            if mat[u][v] == mat[v][u]:
                print('YES')
                for i in range(m + 1):
                    sol.append([u, v][i % 2] + 1)
                print(*sol)
                return
        for [u, v, w] in permutations([0, 1, 2]):
            if mat[u][v] == mat[v][w]:
                left = [[v + 1, w + 1, v + 1, u + 1][i % 4] for i in range((m - 2) // 2)]
                left.reverse()
                middle = [u + 1, v + 1, w + 1]
                right = [[v + 1, u + 1, v + 1, w + 1][i % 4] for i in range((m - 2) // 2)]
                sol += left + middle + right
                print('YES')
                print(*sol)
                return
for t in range(int(input())):
    [n, m] = list(map(int, input().split()))
    solution(n, m, [input() for _ in range(n)])

Solution (Python):
from itertools import permutations

def solution(n, m, mat):
    sol = []
    if m % 2 == 1:
        print('YES')
        for i in range(m + 1):
            sol.append(i % 2 + 1)
        print(*sol)
        return
    elif n == 2 and mat[0][1] != mat[1][0]:
        print('NO')
        return
    elif n == 2:
        print('YES')
        for i in range(m + 1):
            sol.append(i % 2 + 1)
        print(*sol)
        return
    else:
        for [u, v] in [[0, 1], [0, 2], [1, 2]]:
            if mat[u][v] == mat[v][u]:
                print('YES')
                for i in range(m + 1):
                    sol.append([u, v][i % 2] + 1)
                print(*sol)
                return
        for [u, v, w] in permutations([0, 1, 2]):
            if mat[u][v] == mat[v][w]:
                left = [[v + 1, w + 1, v + 1, u + 1][i % 4] for i in range((m - 2) // 2)]
                left.reverse()
                middle = [u + 1, v + 1, w + 1]
                right = [[v + 1, u + 1, v + 1, w + 1][i % 4] for i in range((m - 2) // 2)]
                sol += left
                sol += middle
                sol += right
                print('YES')
                print(*sol)
                return
T = int(input())
for t in range(T):
    [n, m] = list(map(int, input().split()))
    mat = [input() for _ in range(n)]
    solution(n, m, mat)