-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSolution.java
More file actions
115 lines (85 loc) · 2.8 KB
/
Solution.java
File metadata and controls
115 lines (85 loc) · 2.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package hackrank.algorithm.search.connected;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
/**
* Connected Cell in a Grid Challenge
*
* @see https://www.hackerrank.com/challenges/connected-cell-in-a-grid
*/
public class Solution {
public static void main(String[] args) {
Grid grid = readInput(System.in);
System.out.println(grid.findMaxConnected());
}
public static Grid readInput(InputStream stream) {
Scanner scanner = new Scanner(stream);
int rows = scanner.nextInt();
int columns = scanner.nextInt();
int[][] data = new int[rows][columns];
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
data[r][c] = scanner.nextInt();
}
}
scanner.close();
return new Grid(data);
}
}
class Grid {
private int[][] data;
Grid(int[][] data) {
this.data = data;
}
public int findMaxConnected() {
Set<String> visisted = new HashSet<>();
List<Integer> sizes = new ArrayList<>();
for (int r = 0; r < getNumberRows(); r++) {
for (int c = 0; c < getNumberColumns(); c++) {
sizes.add(depthFirstSearch(r, c, visisted));
}
}
return sizes.stream().max(Integer::compareTo).get();
}
private int depthFirstSearch(int row, int column, Set<String> visited) {
if (!hasValue(row, column) || visited.contains((row + "-" + column))) {
return 0;
}
int value = 1;
visited.add(row + "-" + column);
for (Integer[] cell : adjacent(row, column)) {
value += depthFirstSearch(cell[0], cell[1], visited);
}
return value;
}
private List<Integer[]> adjacent(int row, int column) {
int[][] directions =
{ { row - 1, column - 1 }, { row - 1, column }, { row - 1, column + 1 }, { row, column - 1 },
{ row, column + 1 }, { row + 1, column - 1 }, { row + 1, column }, { row + 1, column + 1 } };
List<Integer[]> adjacent = new ArrayList<>();
for (int[] cell : directions) {
if (hasValue(cell[0], cell[1])) {
adjacent.add(new Integer[] { cell[0], cell[1] });
}
}
return adjacent;
}
public boolean hasValue(int row, int column) {
if (row < 0 || row >= getNumberRows()) {
return false;
}
if (column < 0 || column >= getNumberColumns()) {
return false;
}
return data[row][column] == 1;
}
public int getNumberRows() {
return data.length;
}
public int getNumberColumns() {
return data[0].length;
}
}