Matrix sum

4.7

7 votes
Algorithms, Binary Search, Easy, approved
Problem

Assume that you are given an NN matrix A and an integer K. You are required to find the top left and bottom right co-ordinates of the smallest square sub-matrix of A such that the sum of all the elements in the square sub-matrix is K

A sub-matrix of the original matrix having co-ordinates (x1,y1), (x2,y2) is considered to be a square sub-matrix if |x1x2|>=0 and x2x1 = y2y1.

All elements (i,j), where x1ix2, and y1jy2 are considered to be a part of the square (x1,y1), (x2,y2)

Input

  • First line comprises two space-separated integers N and K

  • Each of the next N lines contains N space separated integers. where the jth integer on the ith line denotes A[i][j].

Output :

If there exists a matrix satisfying the above conditions, then on the first line print "YES" (without quotes). On the next line, Print four space-separated integers x1, y1, x2, and y2, which denote the top left and bottom right positions of the smallest square sub-matrix of A such that the sum of all the elements in the square sub-matrix is to K. If there are multiple answers, print any one answer.

If there is no such square sub-matrix, then print "NO" without quotes.

Constraints

  • 1N250

  • 0A[i][j]109

  • 1K1015

Time Limit: 2
Memory Limit: 256
Source Limit:
Explanation

The square matrix having top right co-ordinates (1,1) and bottom right co-ordinates (2,2) has sum equal to 11+1+1+1112. The side length of this square is 2, and no smaller square sub-matrix has sum K

Editor Image

?