Skip to content

Commit 692552e

Browse files
committed
Perfect Squares: BFS, O(n), could use math & reduce to O(sqrt(n)).
1 parent 16ea231 commit 692552e

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

Medium/279_Perfect-Squares.cpp

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#include "../Header.h"
2+
3+
using namespace std;
4+
int numSquares(int n) {
5+
bool *isVisited = new bool[n+1];
6+
memset(isVisited, 0, n+1);
7+
vector<int> squares;
8+
queue<int> BFS;
9+
for (int i = 1; i*i <= n; i++) {
10+
int t = i*i;
11+
if (t == n) return 1;
12+
squares.push_back(t);
13+
BFS.push(t);
14+
isVisited[t] = 1;
15+
}
16+
int curLevelCnt = 0, curLevel = 1, preLevelCnt = squares.size();
17+
18+
while(1) {
19+
curLevel++;
20+
while(preLevelCnt--) {
21+
int num = BFS.front();
22+
BFS.pop();
23+
for (auto square: squares) {
24+
int t = num + square;
25+
if (t == n) return curLevel;
26+
if (t > n) break;
27+
if (!isVisited[t]) {
28+
curLevelCnt++;
29+
isVisited[t] = 1;
30+
BFS.push(t);
31+
}
32+
33+
}
34+
}
35+
preLevelCnt = curLevelCnt;
36+
}
37+
}
38+
int main(int argc, char const *argv[])
39+
{
40+
srand((int)time(NULL));
41+
int num = random(9999);
42+
cout << num << " " << numSquares(num) << endl;
43+
return 0;
44+
}

0 commit comments

Comments
 (0)