forked from gouthampradhan/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMovieRecommend.java
74 lines (66 loc) · 1.56 KB
/
MovieRecommend.java
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package depth_first_search;
import java.util.*;
/**
* Created by gouthamvidyapradhan on 25/02/2017.
* Accepted
*/
public class MovieRecommend
{
Set<Integer> visited = new HashSet<>();
List<Movie> list = new ArrayList<>();
class Movie
{
private int movieId;
private float rating;
private ArrayList<Movie> similarMovies;
public List<Movie> getSimilarMovies()
{
return similarMovies;
}
}
/**
* Main method
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception
{
}
public Set<Movie> getMovieRecommendations (Movie movie, int N)
{
dfs(movie);
Set<Movie> result = new HashSet<>();
Comparator<Movie> cmp = new Comparator<Movie>()
{
@Override
public int compare(Movie o1, Movie o2)
{
return Float.compare(o2.rating, o1.rating);
}
};
Collections.sort(list, cmp);
if(list.size() < N)
{
result.addAll(list);
return result;
}
for(int i = 0; i < N; i ++)
{
result.add(list.get(i));
}
return result;
}
private void dfs(Movie m)
{
visited.add(m.movieId); // mark this visited
List<Movie> movies = m.getSimilarMovies();
for(Movie mo : movies)
{
if(!visited.contains(mo.movieId))
{
list.add(mo);
dfs(mo);
}
}
}
}