You are given a table with rows and columns. Each cell is colored white or black. Considering the shapes created by black cells, what is the maximum border of these shapes?
A shape is a set of connected cells. Two cells are connected if they share an edge. Note that no shape has a hole in it.
Find the maximum number of borders.
Example:
Input: n = 2, m =15, arr = {".....####......",".....#........."};
Output: 4
Approach
Java
public class MaximumBorders {public static void main(String[] args) {int n = 2, m = 15;char arr[][] = { { '.', '.', '.', '.', '.','#', '#', '#','#', '.', '.', '.', '.', '.', '.' },{ '.', '.', '.', '.', '.', '#', '.', '.', '.', '.','.', '.', '.', '.', '.' } };System.out.println(maximumBoarders(n, m, arr));}static int maximumBoarders(int n, int m, char arr[][]) {int ans = 0;for (int i = 0; i < n; i++) {int cu = 0, boru1 = 0, boru2 = 0;for (int j = 0; j < m; j++) {if (i == 0) {if (arr[i][j] == '#') {boru1++;continue;}}if (arr[i][j] != '.') {if (cu == 0) {if (arr[i][j] != arr[i - 1][j])boru1++;else {cu++;}} else {if (arr[i][j] != arr[i - 1][j])boru2++;elsecu++;}}}// update the ansans = Math.max(ans, Math.max(boru1, boru2));}for (int i = 0; i < n; i++) {int cd = 0, bord1 = 0, bord2 = 0;for (int j = 0; j < m; j++) {if (arr[i][j] != '.') {if (cd == 0) {if ((i + 1) < n)if (arr[i][j] != arr[i + 1][j])bord1++;else {cd++;}} else {if ((i + 1) < n)if (arr[i][j] != arr[i + 1][j])bord2++;}}}// update the ansans = Math.max(ans, Math.max(bord1, bord2));}return ans;}}
C++
#include <bits/stdc++.h>using namespace std;int maximumBoarders(int n, int m, char arr[][1000]){int ans = 0;for (int i = 0; i < n; i++){int cu = 0, boru1 = 0, boru2 = 0;for (int j = 0; j < m; j++){if (i == 0){if (arr[i][j] == '#'){boru1++;continue;}}if (arr[i][j] != '.'){if (cu == 0){if (arr[i][j] != arr[i - 1][j])boru1++;else{cu++;}}else{if (arr[i][j] != arr[i - 1][j])boru2++;elsecu++;}}}//update the ansans = max(ans, max(boru1, boru2));}for (int i = 0; i < n; i++){int cd = 0, bord1 = 0, bord2 = 0;for (int j = 0; j < m; j++){if (arr[i][j] != '.'){if (cd == 0){if (arr[i][j] != arr[i + 1][j])bord1++;else{cd++;}}else{if (arr[i][j] != arr[i + 1][j])bord2++;}}}//update the ansans = max(ans, max(bord1, bord2));}return ans;}int main(){int n = 2, m = 15;char arr[1000][1000] = {".....####......",".....#........."};cout << maximumBoarders(n, m, arr) << "\n";return 0;}
Read Interview Questions
Exception Handling Interview Questions
DBMS Interview Questions Set -1
DBMS Interview Questions Set -2
JPA Interview Questions Set -1
Hahaha
ReplyDelete