-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path279_perfect_square.java
More file actions
40 lines (35 loc) · 1.16 KB
/
279_perfect_square.java
File metadata and controls
40 lines (35 loc) · 1.16 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
/* Solution 01: BFS */
class Solution {
public int numSquares(int n) {
if (n < 0)
return 0;
List<Integer> dict = new ArrayList<>();
for (int i = 1; i * i <= n; i++)
dict.add(i * i);
boolean[] visited = new boolean[n + 1];
for (int i = 0; i < visited.length; i++)
visited[i] = false;
Queue<Integer> queue = new LinkedList<>();
queue.add(0);
visited[0] = true;
int level = -1;
while (! queue.isEmpty()) {
int levelSize = queue.size();
level ++;
for (int i = 0;i < levelSize;i ++) {
int current = queue.poll();
if (current == n) {
return level;
}
for (int j = 0; j < dict.size(); j++) {
int newNum = current + dict.get(j);
if (newNum > n || visited[newNum])
continue;
visited[newNum] = true;
queue.add(current + dict.get(j));
}
}
}
return 0;
}
}