0% found this document useful (0 votes)
5 views2 pages

Graphs3 Notes

The document provides a Java implementation of the breadth-first search (BFS) algorithm for traversing a graph. It also describes a problem involving counting the number of islands in a 2D binary grid, where '1's represent land and '0's represent water, with examples illustrating the input and expected output. Constraints on the grid dimensions are specified, ensuring that the grid is within a certain size.

Uploaded by

explorist25
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

Graphs3 Notes

The document provides a Java implementation of the breadth-first search (BFS) algorithm for traversing a graph. It also describes a problem involving counting the number of islands in a 2D binary grid, where '1's represent land and '0's represent water, with examples illustrating the input and expected output. Constraints on the grid dimensions are specified, ensuring that the grid is within a certain size.

Uploaded by

explorist25
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

20 July 2024 12:01

public void bfs(int src, Set<Integer> vis) {


Queue<Integer> q = new LinkedList<>();
q.add(src);

vis.add(src);

while(!q.isEmpty()) {
int front = q.poll();
System.out.print(front + " ");

List<Integer> neighbourList =
adjList.getOrDefault(front, new ArrayList<>());
for(int neighbour : neighbourList) {
if(!vis.contains(neighbour)) {
q.add(neighbour);
vis.add(neighbour);
}
}
}
}

Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the
number of islands.
An island is surrounded by water and is formed by connecting adjacent lands horizontally or
vertically. You may assume all four edges of the grid are all surrounded by water.

Example 1:
Input: grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
Output: 1
Example 2:
Input: grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
Output: 3

Constraints:
• m == grid.length
• n == grid[i].length
• 1 <= m, n <= 300
• grid[i][j] is '0' or '1'.

New Section 1 Page 1


Example 2:
Input: grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
Output: 3

New Section 1 Page 2

You might also like