[DFS/BFS] Number of Good Leaf Nodes Pairs
문제 설명
You are given the root of a binary tree and an integer distance. A pair of two different leaf nodes of a binary tree is said to be good if the length of the shortest path between them is less than or equal to distance.
Return the number of good leaf node pairs in the tree.d she count for each of the supplied maps?
제한 조건
입출력 예
Example 1

Input: root = [1,2,3,null,4], distance = 3
Output: 1
Explanation: The leaf nodes of the tree are 3 and 4 and the length of the shortest path between them is 3. This is the only good pair.
Example 2
2
import java.util.Scanner;
import java.util.Stack;
public class BessieBadGrassIslands {
private static int R, C;
private static int[][] elevation;
// 대각선 및 상하좌우를 위한 델타 배열
private static int[] dRow = {-1, -1, -1, 0, 0, 1, 1, 1};
private static int[] dCol = {-1, 0, 1, -1, 1, -1, 0, 1};
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
R = sc.nextInt();
C = sc.nextInt();
elevation = new int[R][C];
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
elevation[i][j] = sc.nextInt();
}
}
int islandCount = 0;
// 모든 칸을 순회하며 DFS로 섬의 개수를 셉니다.
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
if (elevation[i][j] > 0) {
dfs(i, j);
islandCount++;
}
}
}
System.out.println(islandCount);
sc.close();
}
private static void dfs(int row, int col) {
Stack<int[]> stack = new Stack<>();
stack.push(new int[]{row, col});
elevation[row][col] = 0; // 방문 처리
while (!stack.isEmpty()) {
int[] current = stack.pop();
int currentRow = current[0];
int currentCol = current[1];
// 8방향 탐색
for (int i = 0; i < 8; i++) {
int newRow = currentRow + dRow[i];
int newCol = currentCol + dCol[i];
if (isValid(newRow, newCol) && elevation[newRow][newCol] > 0) {
stack.push(new int[]{newRow, newCol});
elevation[newRow][newCol] = 0; // 방문 처리
}
}
}
}
private static boolean isValid(int row, int col) {
return row >= 0 && row < R && col >= 0 && col < C;
}
}
__