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 )

Constraints

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 :



title-img


                            Solution in C :

In   Python3  :




#!/bin/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
            else:
                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)
        
print(len(history))        
for i in range(0, len(history)):
    print('{} {} {}'.format(history[i][0], history[i][1], history[i][2]))
                        








View More Similar Problems

Tree: Huffman Decoding

Huffman coding assigns variable length codewords to fixed length input characters based on their frequencies. More frequent characters are assigned shorter codewords and less frequent characters are assigned longer codewords. All edges along the path to a character contain a code digit. If they are on the left side of the tree, they will be a 0 (zero). If on the right, they'll be a 1 (one). Only t

View Solution →

Binary Search Tree : Lowest Common Ancestor

You are given pointer to the root of the binary search tree and two values v1 and v2. You need to return the lowest common ancestor (LCA) of v1 and v2 in the binary search tree. In the diagram above, the lowest common ancestor of the nodes 4 and 6 is the node 3. Node 3 is the lowest node which has nodes and as descendants. Function Description Complete the function lca in the editor b

View Solution →

Swap Nodes [Algo]

A binary tree is a tree which is characterized by one of the following properties: It can be empty (null). It contains a root node only. It contains a root node with a left subtree, a right subtree, or both. These subtrees are also binary trees. In-order traversal is performed as Traverse the left subtree. Visit root. Traverse the right subtree. For this in-order traversal, start from

View Solution →

Kitty's Calculations on a Tree

Kitty has a tree, T , consisting of n nodes where each node is uniquely labeled from 1 to n . Her friend Alex gave her q sets, where each set contains k distinct nodes. Kitty needs to calculate the following expression on each set: where: { u ,v } denotes an unordered pair of nodes belonging to the set. dist(u , v) denotes the number of edges on the unique (shortest) path between nodes a

View Solution →

Is This a Binary Search Tree?

For the purposes of this challenge, we define a binary tree to be a binary search tree with the following ordering requirements: The data value of every node in a node's left subtree is less than the data value of that node. The data value of every node in a node's right subtree is greater than the data value of that node. Given the root node of a binary tree, can you determine if it's also a

View Solution →

Square-Ten Tree

The square-ten tree decomposition of an array is defined as follows: The lowest () level of the square-ten tree consists of single array elements in their natural order. The level (starting from ) of the square-ten tree consists of subsequent array subsegments of length in their natural order. Thus, the level contains subsegments of length , the level contains subsegments of length , the

View Solution →