×

Hourglass problem in Java

In this section, we will discuss the hourglass problem in Java.The aim is to find the largest sum of an hour glass given a 2D matrix.

An hour glass is made up of seven cells arranged in the following pattern.
    A B C
      D
    E F G

Examples:

Input : 1 1 1 0 0 
            0 1 0 0 0 
            1 1 1 0 0 
            0 0 0 0 0 
            0 0 0 0 0 
Output : 7
The hour glass below shows the maximum amount:
1 1 1 
  1
1 1 1
Input : 0 3 0 0 0
           0 1 0 0 0
           1 1 1 0 0
           0 0 2 4 4
           0 0 0 2 4
Output : 11
The hour glass below shows the maximum amount:
1 0 0
  4
0 2 4

Approach:

The concept of the hourglass implies that the number of rows and columns must be equal to three. We may say that counting the total number of hourglasses in a matrix equals counting the number of potential top left cells in an hourglass. In an hourglass, the number of top-left cells equals (R-2)*(C-2). As a result, the total number of hourglasses in a matrix is (R-2)*(C-2).

mat[][] = 2 3 0 0 0 
          0 1 0 0 0
          1 1 1 0 0 
          0 0 2 4 4
          0 0 0 2 0
Possible hour glass are :
2 3 0  3 0 0   0 0 0  
  1      0       0 
1 1 1  1 1 0   1 0 0 


0 1 0  1 0 0  0 0 0 
  1      1      0  
0 0 2  0 2 4  2 4 4 


1 1 1  1 1 0  1 0 0
  0      2      4
0 0 0  0 0 2  0 2 0

Consider each top left cell of an hourglass one at a time. We compute the sum of the hourglass created by each cell. Finally, return the highest sum.

The below is an implementation of the following concept:

Hourglass.java

// Java application for determining the maximum
// hour glass sum in matrix
import java.io.*;
class Hourglass {	
static int R = 5;
static int C = 5;
// Returns the greatest possible sum of
// ar[][] hour glass
static int findMaxSum(int [][]mat)
{
	if (R < 3 || C < 3){
		System.out.println("Not possible");
		System.exit(0);
	}
	//The loop is executed here (R-2)*(C-2)
	// considering several situations
	// hourglass cells in the upper left.
	int max_sum = Integer.MIN_VALUE;
	for (int u = 0; u < R - 2; u++)
	{
		for (int v = 0; v < C - 2; v++)
		{
			// Using mat[u][v] as a benchmark
			// The hour glass's left cell.
			int sum = (mat[u][v] + mat[u][v + 1] +
					mat[u][v + 2]) + (mat[u + 1][v + 1]) +
					(mat[u + 2][v] + mat[u + 2][v + 1] +
					mat[u + 2][v + 2]);
			// If the previous total is less than
			// then update the current total
			// new total in max_sum
			max_sum = Math.max(max_sum, sum);
		}
	}
	return max_sum;
}
	// Driver code
	static public void main (String[] args)
	{
		int [][]mat = {{1, 2, 3, 0, 0},
					{0, 0, 0, 0, 0},
					{2, 1, 4, 0, 0},
					{0, 0, 0, 0, 0},
					{1, 1, 0, 1, 0}};
		int res = findMaxSum(mat);
		System.out.println("Hour glass maximum sum = "+ res);
	}	
}

Output:

Hourglass problem in Java

Hourglass.java

import java.util.*;
class Hourglass
{
  public static void main(String[]args)
  {
    Scanner scan = new Scanner(System.in);
    System.out.print("The number of rows: ");
    int rows = scan.nextInt();    
    System.out.print("The number of columns: ");
    int columns = scan.nextInt();
    int[][]matrix = new int[rows][columns];
    System.out.println("Enter the Matrix components: ");    
    for(int u = 0; u < rows; u++)
    {
      for(int v = 0; v < columns; v++)
      {
        matrix[u][v]=scan.nextInt();
      }
    }
    int sum = 0,max = 0;
    for(int u = 0; u < rows - 2; u++)
    {
      for(int v = 0; v < columns - 2; v++)
      {
        sum = (matrix[u][v] + matrix[u][v + 1] + matrix[u][v + 2]) + (matrix[u + 1][v + 1]) + (matrix[u + 2][v] + matrix[u + 2][v + 1] + matrix[u + 2][v + 2]);       
        if(sum > max)
        {
          max = sum;
        }
      }
    }
    System.out.println("The largest amount in the hourglass is: "+max);
  }
}

Output:

Hourglass problem in Java

Related Topics

Singleton Design Pattern in Java

In the singleton pattern, a class that only has one instance and offers a universal point of access is taken into consideration. It can also be defined in another way, a...

4 minutes read.

Java List Interface

List interface is used when we have to order a collection which contains duplicate entries. Like an array, the elements of its implementation classes are retrieved and inserted at a...

2 minutes read.

Java Integer reverseByte() method

The reverseByte() method of Java Integer class returns the value obtained by reversing the order of the bytes in the 2’s complement binary representation. Syntax public static int reverseByte (int i) Parameters The parameter...

1 minute read.

Java Byte Keyword

Byte: The Keyword Byte in Java programming language is a primitive data type.Digital content that is most used for eight bits is called as a byte.The Java Byte Keyword is used...

3 minutes read.

Bottom view of a binary tree in Java

The lowest nodes in their horizontal distance are present and referred to as the bottom view of a binary tree. The horizontal distance between the nodes of a binary tree...

4 minutes read.

Generic Linked List in Java

A linear data structure known as a Linked List stores values in nodes. As we already know, each node has two properties: its value and a link to the node...

6 minutes read.

Difference between final, finally, and finalize()

Difference between final, finally, and finalize() In Java, final, finally and finalize sound similar they are totally different in functionality. Final and finally are the two keywords but the finalize is...

4 minutes read.

How to Convert String to float in Java

How to Convert String to Float in java It is used if you want to perform mathematical operations on the string that contains float number. You can convert String to float...

3 minutes read.

How to Convert long to int in Java

How to Convert long to int in Java When we assign a larger type value to a variable of smaller type, then we need to perform explicit casting for the conversion....

2 minutes read.

Deadlock in Java

Deadlock is when two or more processes wait for the state to do their tasks, but none of them can do so. It is a very common problem that one...

6 minutes read.

Java md5 Hash Example

A 128-bit hash value is generated by the Message Digest Algorithm 5, which is a cryptographic algorithm. A stationary hash value is generated by the hash function from data of...

3 minutes read.

How to Send SMS in Java with Example

Sending SMS messages in Java is a fairly common task, and there are a number of libraries and APIs available to help you do it. One popular option is to...

2 minutes read.

What’s new in Java 12

On March 19th, 2019, the Java 12th edition was released. After releasing this edition, they have decided to release every new edition every six months. This version is the advanced...

5 minutes read.

Various Operation on Queue using Linked List in Java

We keep track of front and rear pointers in a queue data structure. The head of the line points to the first item, and the back to the last. Rear is...

3 minutes read.

Java Map Generic

Java arrays maintain an ordered collection of things, and the index can be used to access the data (an integer). Unlike HashMap, which stores data as a Key/Value pair. We...

3 minutes read.

Differences between Byte Code and Machine Code

This tutorial will discuss the differences between Byte Code and Machine Code. Before that, let's try to know what byte and machine code is. Introduction Every computer has a set of instructions...

4 minutes read.

Non-primitive data types in Java

The kind of data stored in the variable is determined by its type. The type describes the data category (different sizes and values). These are not already built into the devices....

4 minutes read.

Java Pass-by-Reference

In Java, passing parameters can be done using one of two fundamental methods. Pass-by-value is used for the first and pass-by-reference is used for the second. One thing to keep...

2 minutes read.

Convert milliseconds to date in Java

In Java, we frequently need to convert milliseconds into Dates with several formats, including dd MM yyyy and dd MM yyyy HH:mm:ss:SSS Z, among others. The Date class is one of the most...

4 minutes read.

Best Java IDE

Applications for desktop, workplace, smartphone, and the internet can be created using Java, one of the most popular programming languages. Java will undoubtedly be a popular programming language for so...

5 minutes read.