Press "Enter" to skip to content

Posts published in “Graph”

花花酱 LeetCode 785. Is Graph Bipartite?

Video is forĀ čŠ±čŠ±é…± LeetCode 886. Possible Bipartition, but the algorithm is exact the same.

Problem

https://leetcode.com/problems/is-graph-bipartite/

Given an undirectedĀ graph, returnĀ trueĀ if and only if it is bipartite.

Recall that a graph isĀ bipartiteĀ if we can split it’s set of nodes into two independentĀ subsets A and B such that every edge in the graph has one node in A and another node in B.

The graph is given in the following form:Ā graph[i]Ā is a list of indexesĀ jĀ for which the edge between nodesĀ iĀ andĀ jĀ exists.Ā  Each node is an integer betweenĀ 0Ā andĀ graph.length - 1.Ā  There are no self edges or parallel edges:Ā graph[i]Ā does not containĀ i, and it doesn’t contain any element twice.

Example 1:
Input: [[1,3], [0,2], [1,3], [0,2]]
Output: true
Explanation: 
The graph looks like this:
0----1
|    |
|    |
3----2
We can divide the vertices into two groups: {0, 2} and {1, 3}.
Example 2:
Input: [[1,2,3], [0,2], [0,1,3], [0,2]]
Output: false
Explanation: 
The graph looks like this:
0----1
| \  |
|  \ |
3----2
We cannot find a way to divide the set of nodes into two independent subsets.

 

Note:

  • graphĀ will have length in rangeĀ [1, 100].
  • graph[i]Ā will contain integers in rangeĀ [0, graph.length - 1].
  • graph[i]Ā will not containĀ iĀ or duplicate values.
  • The graph is undirected: if any elementĀ jĀ is inĀ graph[i], thenĀ iĀ will be inĀ graph[j].

Solution: Graph Coloring

For each node

  • If has not been colored, color it to RED(1).
  • Color its neighbors with a different color RED(1) to BLUE(-1) or BLUE(-1) to RED(-1).

If we can finish the coloring then the graph is bipartite. All red nodes on the left no connections between them and all blues nodes on the right, again no connections between them. red and blue nodes are neighbors.

Time complexity: O(V+E)

Space complexity: O(V)

C++ / DFS

Related Problem

花花酱 LeetCode 863. All Nodes Distance K in Binary Tree

Problem

题ē›®å¤§ę„ļ¼šē»™ä½ äø€ę£µäŗŒå‰ę ‘ļ¼ˆę ¹ē»“ē‚¹rootļ¼‰å’Œäø€äøŖtarget节ē‚¹ć€‚čæ”å›žę‰€ęœ‰åˆ°targetēš„č·ē¦»äøŗKēš„节ē‚¹ć€‚

We are given a binary tree (with root nodeĀ root), aĀ targetĀ node, and an integer value K.

Return a list of the values of allĀ nodes that have a distanceĀ KĀ from theĀ targetĀ node.Ā  The answer can be returned in any order.

Example 1:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, K = 2
Output: [7,4,1]
Explanation: 
The nodes that are a distance 2 from the target node (with value 5)
have values 7, 4, and 1.

Note that the inputs "root" and "target" are actually TreeNodes.
The descriptions of the inputs above are just serializations of these objects.

Note:

  1. The given tree is non-empty.
  2. Each node in the tree has unique valuesĀ 0 <= node.val <= 500.
  3. TheĀ targetĀ node is a node in the tree.
  4. 0 <= K <= 1000.

Solution1: DFS + BFS

Use DFS to build the graph, and use BFS to find all the nodes that are exact K steps from target.

Time complexity: O(n)

Space complexity: O(n)

C++

Array version

Solution 2: Recursion

Recursively compute the distance from root to target, and collect nodes accordingly.

Time complexity: O(n)

Space complexity: O(n)

 

花花酱 LeetCode 847. Shortest Path Visiting All Nodes

Problem

题ē›®å¤§ę„ļ¼šę±‚锶ē‚¹č¦†ē›–ēš„ęœ€ēŸ­č·Æå¾„ć€‚

https://leetcode.com/problems/shortest-path-visiting-all-nodes/description/

An undirected, connected graph of N nodes (labeledĀ 0, 1, 2, ..., N-1) is given asĀ graph.

graph.length = N, andĀ j != iĀ is in the listĀ graph[i]Ā exactly once, if and only if nodesĀ iĀ andĀ jĀ are connected.

Return the length of the shortest path that visits every node. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges.

Example 1:

Input: [[1,2,3],[0],[0],[0]]
Output: 4
Explanation: One possible path is [1,0,2,0,3]

Example 2:

Input: [[1],[0,2,4],[1,3,4],[2],[1,2]]
Output: 4
Explanation: One possible path is [0,1,4,2,3]

Solution: BFS

Time complexity: O(n*2^n)

Space complexity: O(n*2^n)

C++

C++ / vector

Related Problems

花花酱 LeetCode 841. Keys and Rooms

Problem

There areĀ NĀ rooms and you start in roomĀ 0.Ā  Each room has a distinct number inĀ 0, 1, 2, ..., N-1, and each room may haveĀ some keys to access the next room.

Formally, each roomĀ iĀ has a list of keysĀ rooms[i], and each keyĀ rooms[i][j]Ā is an integer inĀ [0, 1, ..., N-1]Ā whereĀ N = rooms.length.Ā  A keyĀ rooms[i][j] = vĀ opens the room with numberĀ v.

Initially, all the rooms start locked (except for roomĀ 0).

You can walk back and forth between rooms freely.

ReturnĀ trueĀ if and only if you can enterĀ every room.

Example 1:

Input: [[1],[2],[3],[]]
Output: true
Explanation:  
We start in room 0, and pick up key 1.
We then go to room 1, and pick up key 2.
We then go to room 2, and pick up key 3.
We then go to room 3.  Since we were able to go to every room, we return true.

Example 2:

Input: [[1,3],[3,0,1],[2],[0]]
Output: false
Explanation: We can't enter the room with number 2.

Note:

  1. 1 <= rooms.length <=Ā 1000
  2. 0 <= rooms[i].length <= 1000
  3. The number of keys in all rooms combined is at mostĀ 3000.

Solution: DFS

Time complexity: O(V + E)

Space complexity: O(V)

C++

 

花花酱 LeetCode 827. Making A Large Island

Problem

In a 2D grid ofĀ 0s andĀ 1s, we change at most oneĀ 0Ā to aĀ 1.

After, what is the size of the largest island?Ā (An island is a 4-directionally connected group ofĀ 1s).

Example 1:

Input: [[1, 0], [0, 1]]
Output: 3
Explanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3.

Example 2:

Input: [[1, 1], [1, 0]]
Output: 4
Explanation: Change the 0 to 1 and make the island bigger, only one island with area = 1.

Example 3:

Input: [[1, 1], [1, 1]]
Output: 4
Explanation: Can't change any 0 to 1, only one island with area = 1.

Notes:

  • 1 <= grid.length = grid[0].length <= 50.
  • 0 <= grid[i][j] <= 1.

Solution

Step 1: give each connected component a unique id and count its ara.

Step 2: for each 0 zero, check its 4 neighbours, sum areas up by unique ids.

Time complexity: O(n*m)

Space complexity: O(n*m)

C++