Flower Planting With No Adjacent - Graph - Easy - LeetCode
💻 coding

Flower Planting With No Adjacent - Graph - Easy - LeetCode

1 min read 295 words
1 min read
ShareWhatsAppPost on X
  • 1The problem involves planting flowers in gardens connected by paths, ensuring no two adjacent gardens have the same flower type.
  • 2Each garden can have one of four flower types, and the solution guarantees that a valid arrangement always exists.
  • 3The algorithm uses a graph representation to efficiently assign flower types while adhering to the adjacency constraints.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The problem involves planting flowers in gardens connected by paths, ensuring no two adjacent gardens have the same flower type."

— Flower Planting With No Adjacent - Graph - Easy - LeetCode

You have n gardens, labeled from 1 to n, and an array paths where paths[i] = [xi, yi] describes the existence of a bidirectional path from garden xi to garden yi. In each garden, you want to plant one of 4 types of flowers.

There is no garden that has more than three paths coming into or leaving it.

Your task is to choose a flower type for each garden such that, for any two gardens connected by a path, they have different types of flowers.

Return any such a choice as an array answer, where answer[i] is the type of flower planted in the (i+1)th garden. The flower types are denoted 1, 2, 3, or 4. It is guaranteed an answer exists.

Example 1:

Input: n = 3, paths = [[1,2],[2,3],[3,1]] Output: [1,2,3] Example 2:

Input: n = 4, paths = [[1,2],[3,4]] Output: [1,2,1,2] Example 3:

Input: n = 4, paths = [[1,2],[2,3],[3,4],[4,1],[1,3],[2,4]] Output: [1,2,3,4]

Constraints:

1 <= n <= 104 0 <= paths.length <= 2 * 104 paths[i].length == 2 1 <= xi, yi <= n xi != yi No garden has four or more paths coming into or leaving it.

public class Solution {
 Dictionary<int,List<int>> graph = new Dictionary<int,List<int>>();
 HashSet<int> visited = new HashSet<int>(); 
 private void AddVertex(int v){
 graph.Add(v,new List<int>());
 }
 
 private void AddEdge(int s, int d){
 var sEdges = graph[s];
 var dEdges = graph[d];
 
 sEdges.Add(d);
 dEdges.Add(s);
 graph[s]=sEdges;
 graph[d]=dEdges;
 
 }
 
 public int[] GardenNoAdj(int n, int[][] paths) {
 for(int i=1;i<=n;i++){
 AddVertex(i);
 }
 
 for(int i=0;i<paths.Length;i++){
 AddEdge(paths[i][0],paths[i][1]);
 }
 
 var ans = new int[n];
 
 for(int i=1;i<=n;i++){
 var colors = new int[5]; 
 foreach(var item in graph[i]){ 
 colors[ans[item-1]]=1;
 }
 
 for(int j=4;j>=1;j--){
 if(colors[j]!=1){
 ans[i-1]=j;
 }
 }
 }
 
 
 return ans;
 }
 
}

t

Time Complexity: O(V.E)

Space Complexity: O(V)

Where V and E are the vertices and Edges of graph.

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 15 October 2020 · 1 min read · 295 words

Part of AskGif Blog · coding

You might also like