JPMORGAN Coding Question β Solved
Given a matrix of size m * n, where m denotes the number of rows (starting with index 0) and n denotes the number of columns (starting with index 0). The elements in the matrix are populated with values either 1 or 0. A 1 indicates the matrix position is available for establishing the connection, and a 0 indicates the matrix position is not available for establishing the connection.
We need to connect the available adjacent positions vertically, horizontally, and diagonally, and count the number of distinct connections established.
For example, given a matrix of size 3 * 4, the elements are stored as follows:
The expected output is 8.
In the above example, the positions are connected as follows, and hence 8 connections are possible:
1. (0,0) -> (1,1)
2. (2,0) -> (1,1)
3. (1,1) -> (1,2)
4. (1,2) -> (0,3)
5. (1,2) -> (1,3)
6. (1,2) -> (2,3)
7. (0,3) -> (1,3)
8. (1,3) -> (2,3)
Input:
- m: integer representing the number of rows
- n: integer representing the number of columns
- matrix: m * n matrix
Output:
- r: integer representing the total number of connections
Constraints:
- 0 < m, n < 100
- Connection is always between two adjacent cells (horizontally, vertically, or diagonally).
Asked in:
JPMORGAN