Created
May 14, 2021 16:50
-
-
Save outro56/604606b0269bb8d99d0e694da51ead74 to your computer and use it in GitHub Desktop.
Contiguous Regions In Matrix
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static String point(int x, int y) { | |
return String.format("%sx%s", x, y); | |
} | |
public static int contiguousRegions(int[][] matrix) { | |
var seen = new HashSet<String>(); | |
var count = 0; | |
for (int i = 0; i < matrix.length; ++i) { | |
for (int k = 0; k < matrix[0].length; ++ k) { | |
int v = matrix[i][k]; | |
count += dfsVisit(i, k, matrix, v, seen) > 0 ? 1 : 0; | |
} | |
} | |
return count; | |
} | |
public static int dfsVisit(int i, int k, int[][] matrix, int v, HashSet<String> seen) { | |
if (matrix[i][k] != v || !seen.add(point(i, k))) { | |
return 0; | |
} | |
int c = 1; | |
if (i + 1 < matrix.length) { | |
c += dfsVisit(i + 1, k, matrix, v, seen); | |
} | |
if (i - 1 >= 0) { | |
c += dfsVisit(i - 1, k, matrix, v, seen); | |
} | |
if (k + 1 < matrix[0].length) { | |
c += dfsVisit(i, k + 1, matrix, v, seen); | |
} | |
if (k - 1 >= 0) { | |
c += dfsVisit(i, k - 1, matrix, v, seen); | |
} | |
return c; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment