Collect Maximum Coins from Matrix

You are provided with a matrix consisting of 'M' rows and 'N' columns. Each cell in this matrix either contains a coin or is empty.

Your task is to collect the maximum number of coins following these rules: You are allowed to visit every boundary cell that contains a coin and collect it. Additionally, from a boundary coin, you can collect coins from one of the four directly adjacent cells.

Example:

Input:
Matrix of size 3 * 5:
0 1 1 0 0
0 1 0 1 0
1 0 0 0 0
Output:
4
Explanation:

In this matrix, there are five coins, but only four can be collected. The coin at (0, 1) is on the boundary and after collecting it, you can also collect the coin at (1, 1) since it's adjacent. You can also collect the coin at (2, 0) from the boundary. However, the coin at (1, 3) can't be collected since it is neither on the boundary nor adjacent to a boundary coin.

Input:

The first line of the input includes an integer 'T' which represents the number of test cases. Each test case has the following structure:
The first line contains two integers, 'M' and 'N', representing the rows and columns of the matrix.
The next 'M' lines each contain 'N' integers representing the matrix elements (coins in this context).

Output:

For each test case, output the maximum number of coins that can be collected.
Each output should be on a new line for each test case.

Constraints:

  • 1 ≤ T ≤ 10
  • 1 ≤ M, N ≤ 200
  • Matrix[i][j] is either 0 or 1 (where 1 represents a coin).
Note:
You are not required to print anything; it has already been taken care of. Just implement the function and return the result.
AnswerBot
4mo

Given a matrix with coins and empty cells, collect maximum coins from boundary cells and adjacent cells.

  • Iterate through the boundary cells and collect coins from them and their adjacent cells

  • Keep trac...read more

Help your peers!
Select
Add answer anonymously...
CommVault Full Stack Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits