-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path279.perfect-squares-bfs.c
More file actions
98 lines (76 loc) · 1.87 KB
/
279.perfect-squares-bfs.c
File metadata and controls
98 lines (76 loc) · 1.87 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
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/**
279. Perfect Squares
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.
Example 1:
Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.
Example 2:
Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.
*/
// gcc 279.perfect-squares-bfs.c queue.c hashtable.c
#include <stdio.h>
#include <stdlib.h>
#include "queue.h"
#include "hashtable.h"
#define SIZE 1024
int numSquares(int n)
{
Queue *q = queueCreate();
int maxPos = 1;
for (; maxPos < 1024; maxPos++)
{
int *num = (int *)malloc(sizeof(int));
*num = maxPos * maxPos;
if (*num == n)
return 1;
if (*num > n)
{
--maxPos;
break;
}
queueEnqueue(q, num);
}
int count = 0;
void **hashTable = hashTableCreate();
while (!queueIsEmpty(q))
{
++count;
size_t levelCount = queueSize(q);
while (levelCount-- > 0)
{
int *sum = queueFront(q);
if (*sum == n)
return count;
for (int i = 1; i * i + *sum <= n; i++)
{
int *num = (int *)malloc(sizeof(int));
*num = *sum + i * i;
if (*num == n)
{
queueFree(q);
return count + 1;
}
char *key = (char *)malloc(sizeof(char) * 16);
sprintf(key, "%d", *num);
if (lookup(hashTable, 0, key, NULL) == NULL)
{
queueEnqueue(q, num);
lookup(hashTable, 1, key, num);
}
free(key);
}
free(sum);
queueDequeue(q);
}
}
return count;
}
int main()
{
int res = numSquares(12);
printf("res: %d\n", res);
return 0;
}