Sam's Puzzle (Approximate)

Problem Statement :

Sam invented a new puzzle game played on an n x n matrix named puzzle, where each cell contains a unique integer in the inclusive range between 1 and n^2. The coordinate of the top-left cell is (1, 1).

The Moves

A move consists of two steps:

Choose a sub-square of puzzle.
Rotate the sub-square in the clockwise direction.

Good Pairs of Cells

A pair of cell is good if one of the following is true:

They're located in the same row and the number in the left cell is less than the number in the right cell.
They're located in the same column and the number in the upper cell is less than the number in the lower cell.
The diagram below depicts all the good pairs of cells located in the same row:

Goodness of a Square

We define the goodness of a sub-square to be the total number of good pairs of cells in the sub-square.

The Goal

Given the initial value of puzzle, maximize its goodness as much as is possible by performing a sequence of at most 500  moves. Then print the necessary moves according to the Output Format specified below.

Input Format

The first line contains an integer denoting n. Each of the n subsequent lines contains n space-separated integers. The jth integer in the ith line denotes the cell located in coordinate (i, j )


1  <=  n   <=  30
Each cell contains a unique number in the inclusive range between 1 and n^2.

Output Format

Print the following lines of output:

On the first line, print an integer, m, denoting the number of moves necessary to maximize the goodness of puzzle. Recall that this number must be <= 500 .
For each move, print three space-separated integers describing its respective ,i , j and k values on a new line. Recall that a move is described as the clockwise rotation of a k x k  sub-square whose top-left corner is located at coordinate  ( i, j ).

Solution :


                            Solution in C :

In   Python3  :


import math
import os
import random
import re
import sys
import itertools  
import time 

def score(a):
    count = 0 
    for r in range(len(a)):
        for ind in itertools.combinations(range(len(a)), 2):
            if a[r][ind[0]] < a[r][ind[1]]:
                count += 1
    for c in range(len(a[0])):
        for ind in itertools.combinations(range(len(a[0])), 2):
            if a[ind[0]][c] < a[ind[1]][c]:
                count += 1
    return count

def rotate(a, r, c, d):
    seg   = [[a[i][c+j] for i in range(r+d, r-1, -1)] for j in range(d+1)]
    for i in range(d+1):
        for j in range(d+1):
            a[r+i][c+j] = seg[i][j]

def undo(a, r, c, d):
    seg   = [[a[r+i][j] for i in range(d+1)] for j in range(c+d, c-1, -1)]
    for i in range(d+1):
        for j in range(d+1):
            a[r+i][c+j] = seg[i][j]
def getRandom():
    r = random.randint(0, len(a)-2)
    c = random.randint(0, len(a)-2)
    d = random.randint(1, len(a)-1-max(r,c))
    return r, c, d

def countDes(a):
    arrayMax = []
    for i in range(len(a[0])-1):
        count  = 1
        curI   = 0 
        curMax = 1
        posMax = 0
        for j in range(1, len(a)):
            if a[j][i] < a[j-1][i]: 
                count+= 1
                if j == len(a) - 1:
                    if count > curMax:
                        curMax = count
                        posMax = curI
                if count > curMax:
                    curMax = count
                    posMax = curI
                count = 1
                curI  = j 
                        # length  #r     #c
        arrayMax.append([curMax, posMax, i])
    return arrayMax

def processNotRandom(a, getArray, history):
    maxPos  = -1
    maxScore = score(a)

    for i in range(len(getArray)):
        r = getArray[i][1]
        c = getArray[i][2]
        d = min(len(a)-1-max(r,c), getArray[i][0])
        rotate(a, r, c, d)
        sc = score(a)
        if sc > maxScore:
            maxPos   = i
            maxScore = sc
        undo(a, r, c, d)    
    if maxPos != -1:
        r = getArray[maxPos][1]
        c = getArray[maxPos][2]
        d = min(len(a)-1-max(r,c), getArray[maxPos][0])
        rotate(a, r, c, d)
        history.append([r+1, c+1, d+1])

n = int(input())
a = []

for _ in range(n):
    a.append(list(map(int, input().rstrip().split())))

# Write Your Code Here
curMax = score(a)
curSc  = curMax
start  = time.time()
Beta     = 0.8
Beta_increase = 0.8
history = []
maxScore  = score(a)
maxPos = -1
i = 0

while time.time() - start < 8.0 and len(history) < 500:

    r, c, d = getRandom()
    numRotate = 0
    for j in range(3):
            rotate(a, r, c, d)
            sc = score(a)
            if sc > maxScore:
                maxScore  = sc
                numRotate = j + 1
    rotate(a, r, c, d)    
    for j in range(numRotate):
        history.append([r+1, c+1, d+1])
        rotate(a, r, c, d)
for i in range(0, len(history)):
    print('{} {} {}'.format(history[i][0], history[i][1], history[i][2]))

View More Similar Problems

Super Maximum Cost Queries

Victoria has a tree, T , consisting of N nodes numbered from 1 to N. Each edge from node Ui to Vi in tree T has an integer weight, Wi. Let's define the cost, C, of a path from some node X to some other node Y as the maximum weight ( W ) for any edge in the unique path from node X to Y node . Victoria wants your help processing Q queries on tree T, where each query contains 2 integers, L and

View Solution →


We're going to make our own Contacts application! The application must perform two types of operations: 1 . add name, where name is a string denoting a contact name. This must store name as a new contact in the application. find partial, where partial is a string denoting a partial name to search the application for. It must count the number of contacts starting partial with and print the co

View Solution →

No Prefix Set

There is a given list of strings where each string contains only lowercase letters from a - j, inclusive. The set of strings is said to be a GOOD SET if no string is a prefix of another string. In this case, print GOOD SET. Otherwise, print BAD SET on the first line followed by the string being checked. Note If two strings are identical, they are prefixes of each other. Function Descriptio

View Solution →

Cube Summation

You are given a 3-D Matrix in which each block contains 0 initially. The first block is defined by the coordinate (1,1,1) and the last block is defined by the coordinate (N,N,N). There are two types of queries. UPDATE x y z W updates the value of block (x,y,z) to W. QUERY x1 y1 z1 x2 y2 z2 calculates the sum of the value of blocks whose x coordinate is between x1 and x2 (inclusive), y coor

View Solution →

Direct Connections

Enter-View ( EV ) is a linear, street-like country. By linear, we mean all the cities of the country are placed on a single straight line - the x -axis. Thus every city's position can be defined by a single coordinate, xi, the distance from the left borderline of the country. You can treat all cities as single points. Unfortunately, the dictator of telecommunication of EV (Mr. S. Treat Jr.) do

View Solution →

Subsequence Weighting

A subsequence of a sequence is a sequence which is obtained by deleting zero or more elements from the sequence. You are given a sequence A in which every element is a pair of integers i.e A = [(a1, w1), (a2, w2),..., (aN, wN)]. For a subseqence B = [(b1, v1), (b2, v2), ...., (bM, vM)] of the given sequence : We call it increasing if for every i (1 <= i < M ) , bi < bi+1. Weight(B) =

View Solution →