CS1083/Submissions/Final/Q5.java

57 lines
1.7 KiB
Java
Raw Permalink Normal View History

2022-10-07 00:44:12 -03:00
public class Q5 {
//first solution
public static int countInside (int[][] map, int row, int col) {
int initialCount = 0;
for(int[] innerArray: map) {
for(int val: innerArray) {
if (val = 1)
initialCount++;
}
}
countInsideRecursive(row, col, map);
int finalCount = 0;
for(int[] innerArray: map) {
for(int val: innerArray) {
if (val = 1)
finalCount++;
}
}
return finalCount - initialCount;
}
private static void countInsideRecursive(int row, int col, int[][] map) {
map[row][col] = 1;
if (room[row - 1][col] == 0) //up
countInsideRecursive(row - 1, col, map);
if (room[row + 1][col] == 0) //down
countInsideRecursive(row + 1, col, map);
if (room[row][col - 1] == 0) //left
countInsideRecursive(row, col - 1, map);
if (room[row][col + 1] == 0) //right
countInsideRecursive(row, col+1, map);
}
//better solution
private static int countInside(int row, int col, int[][] map) {
map[row][col] = 1;
int count = 0;
if (room[row - 1][col] == 0) {//up
count = 1 + countInside(row - 1, col, map);
}
if (room[row + 1][col] == 0) {//down
count = 1 + countInside(row + 1, col, map);
}
if (room[row][col - 1] == 0) {//left
count = 1 + countInside(row, col - 1, map);
}
if (room[row][col + 1] == 0) {//right
count = 1 + countInside(row, col+1, map);
}
return count;
}
}