-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
53af702
commit 1b2e7bf
Showing
3 changed files
with
58 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
import { findCircleNum } from './findCircleNum'; | ||
|
||
describe('547. Number of Provinces', () => { | ||
test('findCircleNum', () => { | ||
expect( | ||
findCircleNum([ | ||
[1, 1, 0], | ||
[1, 1, 0], | ||
[0, 0, 1], | ||
]), | ||
).toBe(2); | ||
|
||
expect( | ||
findCircleNum([ | ||
[1, 0, 0], | ||
[0, 1, 0], | ||
[0, 0, 1], | ||
]), | ||
).toBe(3); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
type FindCircleNum = (isConnected: number[][]) => number; | ||
|
||
/** | ||
* Accepted | ||
*/ | ||
export const findCircleNum: FindCircleNum = (isConnected) => { | ||
const n = isConnected.length; // Number of cities (or nodes in the graph) | ||
const visited = Array(n).fill(false); // Array to keep track of visited cities | ||
|
||
// DFS function to explore all cities in the current province | ||
const dfs = (i: number) => { | ||
// Traverse all cities | ||
for (let j = 0; j < n; j++) { | ||
// If city 'i' is directly connected to city 'j' and 'j' has not been visited yet | ||
if (isConnected[i][j] === 1 && !visited[j]) { | ||
visited[j] = true; // Mark city 'j' as visited | ||
dfs(j); // Recursively visit all cities connected to city 'j' | ||
} | ||
} | ||
}; | ||
|
||
let provinces = 0; // Variable to count the number of provinces | ||
|
||
// Loop through each city | ||
for (let i = 0; i < n; i++) { | ||
// If the city hasn't been visited yet, it's a new province | ||
if (!visited[i]) { | ||
provinces += 1; // Increment the province count | ||
visited[i] = true; // Mark the current city as visited | ||
dfs(i); // Perform DFS to visit all cities in this province | ||
} | ||
} | ||
|
||
return provinces; // Return the total number of provinces found | ||
}; |