Skip to content

Commit

Permalink
204th Commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Shyam-Chen committed Sep 14, 2024
1 parent 53af702 commit 1b2e7bf
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 1 deletion.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -204,11 +204,12 @@ Ace Coding Interview with 75 Qs
| Graphs - DFS | | |
| ------------------------------------------------------------ | --------------- | ------ |
| 841. Keys and Rooms | [Solution][841] | Medium |
| 547. Number of Provinces | Solution | Medium |
| 547. Number of Provinces | [Solution][547] | Medium |
| 1466. Reorder Routes to Make All Paths Lead to the City Zero | Solution | Medium |
| 399. Evaluate Division | Solution | Medium |

[841]: ./src/page-8/841.%20Keys%20and%20Rooms/canVisitAllRooms.ts
[547]: ./src/page-6/547.%20Number%20of%20Provinces/findCircleNum.ts

| Graphs - BFS | | |
| ---------------------------------------- | -------- | ------ |
Expand Down
21 changes: 21 additions & 0 deletions src/page-6/547. Number of Provinces/findCircleNum.test.ts
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);
});
});
35 changes: 35 additions & 0 deletions src/page-6/547. Number of Provinces/findCircleNum.ts
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
};

0 comments on commit 1b2e7bf

Please sign in to comment.