Sitemap
AShiou

AShiou

Neetcode 150 — Graph

11 min readNov 20, 2026

--

最近為了練習刷題,開始寫 Neetcode 150。以下是我的刷題筆記,主要以 JAVA 來練習,分類及題目來自 Neetcode。

Note

  1. bfs, dfs,例如第一題,第二題
  2. copy + map 避免重複,例如第三題
  3. 從鑽石開始擴散,例如第四題,第五題,第六題,第七題
  4. 畫 graph,例如第八題,第九題
  5. valid tree,例如第十題,第11題
  6. Union find,例如第12題
  7. word ladder,例如第13題

1. Number of Islands

// 1. DFS
// 題目需要算有幾個 islands,可以在遇到 1 時,就把有連起來的 1 都標示成已走過
//
// 假設 grid 是 m * n
// Time complexity: O(mn)
// Space complexity: O(mn)
//
// Dry run
// 01110
// 01010
// 11000
// 00000
//
// (0,1) -> count = 1
// return 1
class Solution {

private int islands = 0;

public int numIslands(char[][] grid) {
boolean[][] visited = new boolean[grid.length][grid[0].length];
int count = 0;
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[0].length; c++) {
if (grid[r][c] == '1' && !visited[r][c]) {
count++;
dfs(r, c, grid, visited);
}
}
}
return count;
}

private void dfs(int r, int c, char[][] grid, boolean[][] visited) {
if (r < 0
|| r >= grid.length
|| c < 0
|| c >= grid[0].length
|| visited[r][c]
|| grid[r][c] == '0') {
return;
}
visited[r][c] = true;
dfs(r+1, c, grid, visited);
dfs(r-1, c, grid, visited);
dfs(r, c+1, grid, visited);
dfs(r, c-1, grid, visited);
}
}

2. Max Area of Island

// 1. dfs
// 這一題和上一題類似,題目一樣有由 1 連接的島嶼,目標是找最大的島嶼
//
// 假設 grid 是 m*n
// Time complexity: O(mn)
// Space complexity: O(mn)
class Solution {
public int maxAreaOfIsland(int[][] grid) {
int max = 0;
boolean[][] visited = new boolean[grid.length][grid[0].length];
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[0].length; c++) {
if (grid[r][c] == 1 && !visited[r][c]) {
max = Math.max(max, dfs(r, c, visited, grid));
}
}
}
return max;
}

private int dfs(int r, int c, boolean[][] visited, int[][] grid) {
if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length) {
return 0;
}
if (grid[r][c] == 0 || visited[r][c]) {
return 0;
}
visited[r][c] = true;
return dfs(r+1, c, visited, grid)
+ dfs(r-1, c, visited, grid)
+ dfs(r, c+1, visited, grid)
+ dfs(r, c-1, visited, grid)
+ 1;
}
}

3. Clone Graph

// 1. BFS
// 利用 BFS 把 node 都複製過,
// 另外因為題目是 undirected graph,可以用 map 來避免重複 new node
//
// 假設有 v 個 node, e 個 edge
// Time complexity: O(v + e)
// Space complexity: O(v)
//
// Dry run
// 1-2
// |
// 3
// 1 -> n:2, 1-2
// 2 -> n:1,3, 1-2-3
// 3 -> n:2
/*
Definition for a Node.
class Node {
public int val;
public List<Node> neighbors;
public Node() {
val = 0;
neighbors = new ArrayList<Node>();
}
public Node(int _val) {
val = _val;
neighbors = new ArrayList<Node>();
}
public Node(int _val, ArrayList<Node> _neighbors) {
val = _val;
neighbors = _neighbors;
}
}
*/

class Solution {
public Node cloneGraph(Node node) {
if (node == null) {
return null;
}
Queue<Node> queue = new ArrayDeque<>();
Map<Node, Node> map = new HashMap<>();
queue.offer(node);
Node result = new Node(node.val);
map.put(node, result);
while (!queue.isEmpty()) {
Node tmp = queue.poll();
Node copyTmp = map.get(tmp);
for (Node n : tmp.neighbors) {
if (!map.containsKey(n)) {
Node copyN = new Node(n.val);
map.put(n, copyN);
queue.offer(n);
}
copyTmp.neighbors.add(map.get(n));
}
}
return result;
}
}
// 2. DFS
//
// Time complexity: O(V+E)
// Space complexity: O(V)
//
// Dry run
// 1-2
// |
// 3
// 1 -> n:2
// 2 -> n:1,3
// 3 -> n:2
class Solution {

private Map<Node, Node> map = new HashMap<>();

public Node cloneGraph(Node node) {
if (node == null) {
return null;
}
return dfs(node);
}

private Node dfs(Node node) {
if (map.containsKey(node)) {
return map.get(node);
}
Node copy = new Node(node.val);
map.put(node, copy);
for (Node n : node.neighbors) {
copy.neighbors.add(dfs(n));
}
return copy;
}
}

4. Islands and Treasure

// 1. BFS
// 題目如果是 -1 return -1,如果是 0 return 0,如果是 INF 要試著走找看看 0
// 可以用 BFS 的方式,從 treasure 開始走,某個 INF 第一次被拜訪時,就是最接近 treasure 的距離
//
// 假設 grid 是 m*n
// Time complexity: O(mn)
// Space complexity: O(mn)
//
// Dry run
// INF, -1, 0, INF
// INF, INF, INF, -1
// INF, -1, INF, -1
// 0, -1, INF, INF
//
// queue={(0,2), (3, 0)}
// INF, -1, 0, 1
// INF, INF, 1, -1
// 1, -1, INF, -1
// 0, -1, INF, INF
//
// queue={(0,3), (1,2), (2,0)}
// INF, -1, 0, 1
// 2, 2, 1, -1
// 1, -1, 2, -1
// 0, -1, INF, INF
//
// queue={(1,1), (2,2), (1,0)}
// 3, -1, 0, 1
// 2, 2, 1, -1
// 1, -1, 2, -1
// 0, -1, 3, INF
//
// queue={(3,2), (0,0)}
// 3, -1, 0, 1
// 2, 2, 1, -1
// 1, -1, 2, -1
// 0, -1, 3, 4
class Solution {
public void islandsAndTreasure(int[][] grid) {
Queue<int[]> queue = new ArrayDeque<>();

for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[0].length; c++) {
if (grid[r][c] == 0) {
queue.offer(new int[]{r, c});
}
}
}

int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
int distance = 0;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
int[] treasure = queue.poll();
int x = treasure[0];
int y = treasure[1];
for (int[] dir : dirs) {
int dx = x + dir[0];
int dy = y + dir[1];
if (dx < 0 || dx >= grid.length
|| dy < 0 || dy >= grid[0].length
|| grid[dx][dy] != Integer.MAX_VALUE) {
continue;
}
grid[dx][dy] = distance + 1;
queue.offer(new int[]{dx, dy});
}
}
distance++;
}
}
}

Get AShiou’s stories in your inbox

Join Medium for free to get updates from this writer.

5. Rotting Fruit

// 1. BFS
// 題目在 matrix 內放了新鮮的水果及爛水果,每分鐘爛水果會把身邊的新鮮水果變成爛水果,
// 問最少需要幾分鐘
// 和上一題很像,從爛水果開始往外擴
//
// 假設 grid 是 m*n
// Time complexity: O(mn)
// Space complexity: O(mn)
//
// Dry run
// 1,1,0
// 0,1,1
// 0,1,2
// queue={(2,2)}, fresh=5
// 1,1,0
// 0,1,2
// 0,2,2
// queue={(1,2), (2,1)}, fresh=3, min=1
// 1,1,0
// 0,2,2
// 0,2,2
// queue={(1,1)}, fresh=2, min=2
// 1,2,0
// 0,2,2
// 0,2,2
// queue={(0,1)}, fresh=1, min=3
// 2,2,0
// 0,2,2
// 0,2,2
// queue={}, fresh=0, min=4
class Solution {
public int orangesRotting(int[][] grid) {
int freshCount = 0;
Queue<int[]> queue = new ArrayDeque<>();
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[0].length; c++) {
if (grid[r][c] == 2) {
queue.offer(new int[]{r, c});
} else if (grid[r][c] == 1) {
freshCount++;
}
}
}
if (freshCount == 0) {
return 0;
}

int[][] dirs = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
int min = 0;

while (!queue.isEmpty()) {
int size = queue.size();
min++;
for (int i = 0; i < size; i++) {
int[] cur = queue.poll();
int x = cur[0];
int y = cur[1];
for (int[] dir : dirs) {
int dx = x + dir[0];
int dy = y + dir[1];
if (dx < 0
|| dx >= grid.length
|| dy < 0
|| dy >= grid[0].length
|| grid[dx][dy] != 1) {
continue;
}
freshCount--;
if (freshCount == 0) {
return min;
}
grid[dx][dy] = 2;
queue.offer(new int[]{dx, dy});
}
}
}
return -1;
}
}

6. Pacific Atlantic Water Flow

// 1.
// 題目紀錄了matrix 各個點的海平面高度,要看哪幾個點可以流到左上和右下。
// 4,2,7,3,4
// 7,4,6,4,7
// 6,3,5,3,6
// 可以用兩個 matrix,一個紀錄可以流到 Pacific,一個紀錄可以流到 Atlantic,
// 從邊邊開始,接著 BFS 看哪些可以流到海洋
//
// 假設 heights 為 m * n
// Time complexity: O(mn)
// Space complexity: O(mn)
//
// Dry run
// 4,2,7,3,4
// 7,4,6,4,7
// 6,3,5,3,6
// pacific
// queue={(0,0),(1,0),(2,0),(3,0),(4,0),(0,1),(0,2)}
// 1,1,1,1,1
// 1,0,0,0,0
// 1,0,0,0,0
// queue={(1,1),(1,3),(1,4)}
// 1,1,1,1,1
// 1,1,0,1,1
// 1,0,0,0,0
// queue={(1,2)}
// 1,1,1,1,1
// 1,1,1,1,1
// 1,0,0,0,0
// atlantic
// queue={(2,0),(2,1),(2,2),(2,3),(2,4),(0,4),(1,4)}
// 0,0,0,0,1
// 0,0,0,0,1
// 1,1,1,1,1
// queue={(1,0),(1,1),(1,2),(1,3)}
// 0,0,0,0,1
// 1,1,1,1,1
// 1,1,1,1,1
// queue={(0,2)}
// 0,0,1,0,1
// 1,1,1,1,1
// 1,1,1,1,1
// result
// 0,0,1,0,1
// 1,1,1,1,1
// 1,0,0,0,0
class Solution {

private int[][] dirs = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}};

public List<List<Integer>> pacificAtlantic(int[][] heights) {
int m = heights.length;
int n = heights[0].length;
boolean[][] pacific = new boolean[m][n];
boolean[][] atlantic = new boolean[m][n];
Queue<int[]> queue = new ArrayDeque<>();
for (int r = 0; r < m; r++) {
pacific[r][0] = true;
queue.offer(new int[]{r, 0});
}
for (int c = 0; c < n; c++) {
pacific[0][c] = true;
queue.offer(new int[]{0, c});
}
bfs(pacific, heights, queue);

for (int r = m - 1; r >= 0; r--) {
atlantic[r][n - 1] = true;
queue.offer(new int[]{r, n - 1});
}
for (int c = n - 1; c >= 0; c--) {
atlantic[m - 1][c] = true;
queue.offer(new int[]{m - 1, c});
}
bfs(atlantic, heights, queue);
List<List<Integer>> result = new ArrayList<>();
for (int r = 0; r < m; r++) {
for (int c = 0; c < n; c++) {
if (pacific[r][c] && atlantic[r][c]) {
result.add(List.of(r, c));
}
}
}
return result;
}

private void bfs(boolean[][] sea, int[][] heights, Queue<int[]> queue) {
int m = heights.length;
int n = heights[0].length;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
int[] cur = queue.poll();
int x = cur[0];
int y = cur[1];
for (int[] dir : dirs) {
int dx = x + dir[0];
int dy = y + dir[1];
if (dx < 0 || dx >= m || dy < 0 || dy >= n || sea[dx][dy]) {
continue;
}
if (heights[dx][dy] >= heights[x][y]) {
queue.offer(new int[]{dx, dy});
sea[dx][dy] = true;
}
}
}
}
}
}

7. Surrounded Regions

// 1. BFS
// 題目有一堆 X 和 O,一堆連在一起的 O 可以形成一個 region,
// 如果 O 的四周都不靠近 edge,那他們可以被改成 X
// 可以反過來想,從邊邊有 O 的開始,遇到的 O 都必須維持 O
// 所以可以用 # 來表示不可被改變的 O
// 再 for loop 全部,把 O 改成 X,把 # 改成 O
//
// 假設 board 為 m*n
// TIme complexity: O(mn)
// Space complexity: O(mn)
//
// Dry run
// XXXX
// XOOX
// XXOX
// XOXX
// queue={(3,1)}
// XXXX
// XOOX
// XXOX
// X#XX
// result
// XXXX
// XXXX
// XXXX
// XOXX
class Solution {
public void solve(char[][] board) {
int m = board.length;
int n = board[0].length;
Queue<int[]> queue = new ArrayDeque<>();
for (int r = 0; r < m; r++) {
for (int c = 0; c < n; c++) {
if (r != 0 && c!= 0 && r != m - 1 && c != n - 1) {
continue;
}
if (board[r][c] == 'O') {
queue.offer(new int[]{r, c});
board[r][c] = '#';
}
}
}
int[][] dirs = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
int[] cur = queue.poll();
int x = cur[0];
int y = cur[1];
for (int[] dir : dirs) {
int dx = x + dir[0];
int dy = y + dir[1];
if (dx < 0 || dx >= m || dy < 0 || dy >= n) {
continue;
}
if (board[dx][dy] != 'O') {
continue;
}
queue.offer(new int[]{dx, dy});
board[dx][dy] = '#';
}
}
}
for (int r = 0; r < m; r++) {
for (int c = 0; c < n; c++) {
if (board[r][c] == 'O') {
board[r][c] = 'X';
} else if(board[r][c] == '#') {
board[r][c] = 'O';
}
}
}
}
}

8. Course Schedule

// 1. Brute Force
// 題目有規定要上幾堂課,並且有一些先決條件,什麼課只能排在什麼課之後
// 如果透過先決條件連線畫 graph,然後把點放到 hashmap,
// 如果點不在,試著畫圖,如果點在,試著用 DFS 找到它
//
// 假設有 n 堂課
// Time complexity: O(n^2)
// Space complexity: O(n)

// 2. BFS
// 先根據先決條件畫圖,adjecency 是接下來的課
// graph[i] = List(...)有條件要關聯的課
// indegree[i] = 有多少先修課
//
// 接下來用 bfs,從 indegree 為 0 的開始放 queue,
// for loop adjecency,讓 adjacency 的 indegree--,直到為 0 時放進 queue
// 最後檢查 count 和 numCourses 是否一致,
// 如果有 node 因為 indegree 不為 0 而無法遍歷,便是無法完成課程。
// 例如有 cycle 時,就會導致在 cycle 內的 course 沒有 indegree 為 0 的時候。
//
// Time complexity: O(V+E)
// Space complexity: O(V+E)
class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
List<List<Integer>> graph = new ArrayList<>();
int[] indegree = new int[numCourses];

for (int i = 0; i < numCourses; i++) {
graph.add(new ArrayList<>());
}

for (int[] prerequisite : prerequisites) {
int course = prerequisite[0];
int pre = prerequisite[1];
graph.get(pre).add(course);
indegree[course]++;
}

Queue<Integer> queue = new ArrayDeque<>();
int count = 0;
for (int i = 0; i < numCourses; i++) {
if (indegree[i] == 0) {
queue.offer(i);
}
}
while (!queue.isEmpty()) {
int course = queue.poll();
count++;
for (int next : graph.get(course)) {
indegree[next]--;
if (indegree[next] == 0) {
queue.offer(next);
}
}
}
return count == numCourses;
}
}

9. Course Schedule II

// 1. BFS
// 和上一題差不多,差在需要回傳課程排序;因此在 bfs 時,可以順便紀錄 course
//
// 假設有 V 堂課, prerequisites 有 E 個
// Time complexity: O(V+E)
// Space complxity: O(V+E)
class Solution {
public int[] findOrder(int numCourses, int[][] prerequisites) {
List<List<Integer>> graph = new ArrayList<>();
int[] indegree = new int[numCourses];
for (int i = 0; i < numCourses; i++) {
graph.add(new ArrayList<>());
}
for (int[] prerequisite : prerequisites) {
int course = prerequisite[0];
int pre = prerequisite[1];
graph.get(pre).add(course);
indegree[course]++;
}
Queue<Integer> queue = new ArrayDeque<>();
for (int i = 0; i < numCourses; i++) {
if (indegree[i] == 0) {
queue.offer(i);
}
}
int[] result = new int[numCourses];
int count = 0;
while (!queue.isEmpty()) {
int course = queue.poll();
result[count] = course;
count++;
for (int next : graph.get(course)) {
indegree[next]--;
if (indegree[next] == 0) {
queue.offer(next);
}
}
}
return count == numCourses ? result : new int[0];
}
}

10. Graph Valid Tree

// 1. BFS
// 如何辨認 graph 是否是 tree 要符合兩個點
// a. 所有 node 要相連結
// b. 不能有 cycle
// 所以可以從 edges 是 n - 1 及 node 都被遍歷過來檢查
//
// 假設有 edges 為 e
// Time complexity: O(n + e)
// Space complexity: O(n + e)
class Solution {
public boolean validTree(int n, int[][] edges) {
if (edges.length != n - 1) {
return false;
}
List<List<Integer>> graph = new ArrayList<>();
boolean[] visited = new boolean[n];
for (int i = 0 ; i < n; i++) {
graph.add(new ArrayList<>());
}
for (int[] edge : edges) {
int a = edge[0];
int b = edge[1];
graph.get(a).add(b);
graph.get(b).add(a);
}
Queue<Integer> queue = new ArrayDeque<>();
queue.offer(0);
visited[0] = true;
while (!queue.isEmpty()) {
int node = queue.poll();
for (int next : graph.get(node)) {
if (!visited[next]) {
visited[next] = true;
queue.offer(next);
}
}
}
for (boolean v : visited) {
if (!v) {
return false;
}
}
return true;
}
}

11. Number of Connected Components in an Undirected Graph

// 1. dfs
// 題目希望算出有幾個 graph,可以先把 graph 建立起來,
// 然後 for loop 每個 node,還沒 visit 過的,就遍歷
//
// Time complexity: O(V+E)
// Space complexity: O(V+E)
// - dfs:O(logV),最差 V
class Solution {
public int countComponents(int n, int[][] edges) {
int count = 0;
List<List<Integer>> graph = new ArrayList<>();
boolean[] visited = new boolean[n];
for (int i = 0; i < n; i++) {
graph.add(new ArrayList<>());
}
for (int[] edge : edges) {
int a = edge[0];
int b = edge[1];
graph.get(a).add(b);
graph.get(b).add(a);
}
for (int i = 0; i < n; i++) {
if (!visited[i]) {
dfs(i, graph, visited);
count++;
}
}
return count;
}

private void dfs(int node, List<List<Integer>> graph, boolean[] visited) {
visited[node] = true;
for (int next : graph.get(node)) {
if (!visited[next]) {
dfs(next, graph, visited);
}
}
}
}

12. Redundant Connection

// 1. Brute Force
// 題目給了一個 graph,試著刪除一個 edge,讓 graph 變成沒有 cycle 的 graph
// 回傳的結果要是 edge array 符合條件的最後
// 可以試著先把 graph 建起來,然後 for loop 刪掉 edge,看看 DFS 是否還是 graph
//
// Time complexity: O(E(V+E))
// Space complexity: O(V+E)

// 2. Union Find
// 試著把 graph 建起來,然後for loop edge把node和node關聯起來,
// 如果新的 edge 是已經關聯過的,則 return edge
//
// Time complexity: O(V+E)
// Space complexity: O(V)
class Solution {
public int[] findRedundantConnection(int[][] edges) {
int n = edges.length;
int[] parent = new int[n + 1];

for (int i = 1; i <= n; i++) {
parent[i] = i;
}

for (int[] edge : edges) {
int u = edge[0];
int v = edge[1];

int rootU = find(parent, u);
int rootV = find(parent, v);

if (rootU == rootV) {
return edge;
}
parent[rootU] = rootV;
}

return new int[0];
}

private int find(int[] parent, int x) {
if (parent[x] != x) {
parent[x] = find(parent, parent[x]);
}
return parent[x];
}
}

13. Word Ladder

// 1. BFS + hashset
// 題目提到會給一個 beginWord,每次只能替換一個字母,讓其對應到 wordList 的其中一個 word
// 直到和 endWord match
// 如果 wordList 沒有 endWord,return false
// 透過 BFS 的方式,找可以對應的下一個 word,塞進 queue 內,直到找到結果。
//
// 假設 wordList 有 N 個單字,每個單字長度 L
// Time complexity: O(NL^2)
// Space complexity: O(NL)
//
// Dry run
// beginWord = "cat", endWord = "sag",
// wordList = ["bat","bag","sag","dag","dot"]
// cat -> bat, wordList = ["bag","sag","dag","dot"]
// bat -> bag, wordList = ["sag","dag","dot"]
// bag -> sag, dag, wordList = ["dot"] -> return 4
class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
Set<String> words = new HashSet<>(wordList);
if (!words.contains(endWord)) {
return 0;
}

Queue<String> queue = new ArrayDeque<>();
queue.offer(beginWord);

int level = 1;
while(!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
String word = queue.poll();

if (word.equals(endWord)) {
return level;
}

char[] chars = word.toCharArray();
for (int j = 0; j < chars.length; j++) {
char original = chars[j];

for (char c = 'a'; c <= 'z'; c++) {
if (c == original) {
continue;
}

chars[j] = c;
String next = new String(chars);
if (words.contains(next)) {
queue.offer(next);
words.remove(next);
}
}
chars[j] = original;
}
}
level++;
}
return 0;
}
}

--

--