-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathFlowerPlantingWithNoAdjacent.java
More file actions
41 lines (39 loc) · 1.05 KB
/
FlowerPlantingWithNoAdjacent.java
File metadata and controls
41 lines (39 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution {
public int[] gardenNoAdj(int n, int[][] paths) {
int output[] = new int[n];
boolean ans=backtrack(1,paths,output,n+1);
return output;
}
public boolean backtrack(int garden,int path[][], int output[],int n)
{
if(garden == n)
return true;
for(int i=1;i<=4;i++)
{
if(isFeasible(garden,path,output,i))
{
output[garden-1]=i;
if(backtrack(garden+1,path,output,n))
{
return true;
}
}
}
return false;
}
public boolean isFeasible(int garden,int path[][],int output[],int color)
{
for(int i=0;i<path.length;i++)
{
if(path[i][0]==garden)
{
if(output[path[i][1]-1]==color) return false;
}
else if(path[i][1]==garden)
{
if(output[path[i][0]-1]==color) return false;
}
}
return true;
}
}