Find alphabet in a Matrix which has maximum number of stars around it

Given a matrix mat consisting of * and lowercase English alphabets, the task is to find the character which has the maximum number of * around it (including diagonal elements too). If two characters have same maximum count, print lexicographically smallest character.

Source :D-E Shaw Interview Experience

Examples:

Input: 
mat[][] = {{'b', '*', '*', '*'}, 
           {'*', '*', 'c', '*'}, 
           {'*', 'a', '*', '*'}, 
           {'*', '*', '*', 'd'}}
Output: a
'a', 'b', 'c' and 'd' are surrounded by 
'7', '3', '7' and '3' stars respectively.
'a' and 'c' are surrounded by maximum stars 
but 'a' is lexicographically smaller than 'c'.

Input: 
mat[][] = {{'*', 'r', '*', '*'}, 
           {'m', 'a', 'z', '*'}, 
           {'l', '*', 'f', 'k'}, 
           {'*', '*', '*', 'd'} }
Output: f


Approach: The idea is to traverse the matrix and if a character is found then calculate the count of stars around it. Check at all 8 positions around it and count the number of starts.

Use a map to keep track of the character and the number of stars surrounding it. Then traverse the map and find the character which is surrounded by maximum stars and is lexicographically smallest.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find alphabet in a Matrix
// which has maximum number of stars
// surrounding it
#include <bits/stdc++.h>
using namespace std;
  
// Function to return the count of stars
// around a particular index
int countStars(int mat[][4], int i, int j, int n)
{
    int count = 0;
  
    int rowNum[] = { -1, -1, -1, 0, 0, 1, 1, 1 };
    int colNum[] = { -1, 0, 1, -1, 1, -1, 0, 1 };
  
    // consider all 8 neighbours
    for (int k = 0; k < 8; k++) {
        int x = i + rowNum[k];
        int y = j + colNum[k];
        if (x >= 0 && x < n && y >= 0 && y < n
            && mat[x][y] == '*')
            count++;
    }
  
    return count;
}
  
// Function to return the character in a Matrix
// which has maximum number of stars around it
char alphabetWithMaxStars(int mat[][4], int n)
{
    unordered_map<char, int> umap;
  
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
  
            // If current element is a character
            if ((mat[i][j] - 97) >= 0
                && (mat[i][j] - 97) < 26) {
                // Count of start surrounding it
                int stars = countStars(mat, i, j, n);
                umap[mat[i][j]] = stars;
            }
        }
    }
  
    int max = -1;
    char result = 'z' + 1;
  
    // Traverse the map
    for (auto x : umap) {
        if (x.second > max || (x.second == max
                               && x.first < result)) {
            max = x.second;
            result = x.first;
        }
    }
  
    return result;
}
  
// Driver code
int main()
{
    int mat[][4] = { { 'b', '*', '*', '*' },
                     { '*', '*', 'c', '*' },
                     { '*', 'a', '*', '*' },
                     { '*', '*', '*', 'd' } };
  
    int n = 4;
  
    cout << alphabetWithMaxStars(mat, n);
  
    return 0;
}

chevron_right


Output:

a

Another approach:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to find alphabet in a Matrix
// which has maximum number of stars
// surrounding it
public class SuperStarLetter {
      
    // Function to return the character in a Matrix
    // which has maximum number of stars around it
    private static char getStarredLetter (char[][] mat) {
        char currentSuperStar = 'a';
        int currentFans = 0;
        for (int i=0 ; i < mat.length ; i++) {
            char[] row = mat[i];
            for (int j = 0 ; j < row.length; j++) {
                char currentChar = row[j];
                if (currentChar != '*') {
                      
                    // Count of start surrounding it
                    int fans = countStars(i, j, mat);
                    if (fans > currentFans) {
                        currentSuperStar = currentChar;
                        currentFans = fans;
                    } else if (fans == currentFans && 
                            currentChar < currentSuperStar) {
                        currentSuperStar = currentChar;
                    }
                }
            }
        }
        return currentSuperStar;
    }
  
    /**
    * Counts the number of stars around the letter at position i,j
    * start at position max(i-1,0),max(j-1,0) and iterate the 3*3 mini matrix
    * while watching out the boundaries of
    * our main matrix. 
    * @param i
    * @param j
    * @param mat
    * @return
    */
    private static int countStars(int i, int j, char[][] mat) {
        int initialRow = i != 0 ? i-1 : i;
        int initialCol = j != 0 ? j-1 : j;
        int stars= 0
        for (int row=initialRow;(row <= i+1) && row < mat.length ; row++) {
            for (int col=initialCol;(col <= j+1) && col < mat.length ; col++) {
                if (mat[row][col] == '*') {
                    stars++;
                }
            }
        }
        return stars;
    }
        //Driver Code
    public static void main(String[] args) {
        char[][] mat = { { 'b', '*', '*', '*' },
                     { '*', '*', 'c', '*' },
                     { '*', 'a', '*', '*' },
                     { '*', '*', '*', 'd' } };
        System.out.println(getStarredLetter(mat));
          
    }
  
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to find alphabet 
# in a Matrix which has maximum 
# number of stars surrounding it
  
# Function to return the character 
# in a Matrix which has maximum
# number of stars around it
def getStarredLetter (mat) :
    currentSuperStar = 'a'
    currentFans = 0
    for i in range(len(mat)) :
        row = mat[i]
          
        for j in range(len(row)) :
              
            currentChar = row[j]
            if (currentChar != '*') :
                      
                # Count of start surrounding it
                fans = countStars(i, j, mat)
                if (fans > currentFans) :
                    currentSuperStar = currentChar
                    currentFans = fans
                  
                elif (fans == currentFans and 
                      currentChar < currentSuperStar) :
                    currentSuperStar = currentChar;
                      
    return currentSuperStar;
      
"""
    * Counts the number of stars around the 
    * letter at position i,j start at position 
    * max(i-1,0),max(j-1,0) and iterate the 3*3 
    * mini matrix while watching out the boundaries 
    * of our main matrix. 
    * @param i
    * @param j
    * @param mat
    * @return
"""
def countStars(i, j, mat) :
      
    if i != 0 :
        initialRow = i - 1
    else
        initialRow = i
          
      
    if j != 0 :
        initialCol = j - 1
    else
        initialCol = j
          
    stars = 0
      
    row = initialRow
      
    while ((row <= i + 1) and (row < len(mat))):
        col = initialCol
        while ((col <= j + 1) and (col < len(mat))):
            if (mat[row][col] == '*') :
                  
                stars += 1
              
            col += 1
              
        row += 1
          
    return stars
      
# Driver Code
if __name__ == "__main__" :
      
    mat = [ [ 'b', '*', '*', '*' ],
            [ '*', '*', 'c', '*' ],
            [ '*', 'a', '*', '*' ],
            [ '*', '*', '*', 'd' ] ]
              
    print(getStarredLetter(mat))
          
# This code is contributed by Ryugaa 

chevron_right


Output:

a


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : prmdk, Ryuga