Distance between closest pair of islands
Given a grid[][] containing 0s and 1s, where ‘0’ represents water and ‘1’ represents land. Given that an island is a group of land (1s) surrounded by water (0s) on all sides.
The task is to find the distance between the two closest islands such that:
- Distance between two island is the minimum number of ‘0’ between two islands.
- Only 4 – directional movement is allowed.
- There are at least 2 islands present in the grid.
Examples:
Input: grid = {{1, 1, 0, 1, 1},
{1, 1, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 1, 1, 1}}
Output: 1
Explanation: There are three islands present in the grid.
Nearest pair of islands have only 1 zero (bolded in input grid) in between them.Input: grid = {{1, 0, 0, 0, 1},
{1, 1, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 1, 1, 1}}
Output: 2
Explanation: There are three islands present in the grid.
Nearest pair of islands have 2 zeroes in between them (depicted by bold 0 in input grid).
In this case there are multiple pair of islands having distance 2 between them.
Naive Approach:
The intuition is to find minimum distance between every possible pair of islands and return the minimum of all the distances, using DFS.
To find minimum distance between 2 island follow the below steps:
- Store the coordinates of every islands separately in List / vector.
- Create a boolean visited array to mark if an element has been visited.
- Traverse the grid and if an element is ‘1’ and unvisited then call dfs to get all the elements corresponding island
- Store coordinates of this island in list.
- Find the minimum distance between every pair of island in the list.
- For every pair of island in list find the minimum distance between them.
- distance between 2 island will be the minimum distance between every pair of points in both islands.
- For every pair of island in list find the minimum distance between them.
- Return the minimum of all the distances between islands.
Below is the code for the implementation of approach:
Java
// Java code to implement the approachimport java.util.*; class GFG { static int row; static int col; // A class to represent coordinates of // element in matrix static class Pair { int x; int y; Pair(int x, int y) { this.x = x; this.y = y; } } // Function to find closest distance static void closestDistance(int[][] grid) { row = grid.length; col = grid[0].length; // List of coordinates // of all the islands ArrayList<ArrayList<Pair> > list = findIslands(grid); // Number of islands int n = list.size(); // Variable to store // minimum of all distances int ans = Integer.MAX_VALUE; for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { ArrayList<Pair> island1 = list.get(i); ArrayList<Pair> island2 = list.get(j); int dist = findDistance(island1, island2); ans = Math.min(dist, ans); } } System.out.println(ans); } // Function to find and // store all islands in list static ArrayList<ArrayList<Pair> > findIslands(int[][] grid) { boolean[][] visited = new boolean[row][col]; ArrayList<ArrayList<Pair> > list = new ArrayList<>(); for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if (grid[i][j] == 1 && !visited[i][j]) { ArrayList<Pair> island = new ArrayList<>(); dfs(visited, grid, i, j, island); list.add(island); } } } return list; } // Function to find min distance // between 2 islands static int findDistance(ArrayList<Pair> island1, ArrayList<Pair> island2) { int dist = Integer.MAX_VALUE; for (int i = 0; i < island1.size(); i++) { Pair point1 = island1.get(i); for (int j = 0; j < island2.size(); j++) { Pair point2 = island2.get(j); int distp1p2 = Math.abs(point1.x - point2.x) + Math.abs(point1.y - point2.y) - 1; dist = Math.min(dist, distp1p2); } } return dist; } static int[] dirx = { 0, 1, 0, -1 }; static int[] diry = { 1, 0, -1, 0 }; static void dfs(boolean[][] visited, int[][] grid, int i, int j, ArrayList<Pair> island) { visited[i][j] = true; island.add(new Pair(i, j)); for (int idx = 0; idx < 4; idx++) { int x = i + dirx[idx]; int y = j + diry[idx]; if (isValid(x, y) && grid[x][y] == 1 && !visited[x][y]) { dfs(visited, grid, x, y, island); } } } // Function to check if // a point is inside grid static boolean isValid(int x, int y) { if (x < 0 || x >= row || y < 0 || y >= col) return false; return true; } // Driver code public static void main(String[] args) { int[][] grid = { { 1, 0, 0, 0, 1 }, { 1, 1, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 1, 1, 1 } }; closestDistance(grid); }} |
2
Time Complexity: O(N4)
Auxiliary Space: O(N2)
Efficient Approach:
The idea is that instead of finding distance between each island pair from the naive approach, optimize the task using Depth-first-search and breadth-first-search traversal techniques for individual operations, as mentioned below:
- First find all islands in the Grid using DFS
- Then find the minimum distance island pair among these, using BFS.
Follow the steps to solve the problem using the above efficient approach:
- Create two 2d arrays ‘visited’ and ‘distance’ initialized by 0. Distance array will be to store the distance to nearest island.
- Traverse the grid and if an element is ‘1’ then call dfs to mark the corresponding element in visited array by any number other than 0.
- Mark each island in the visited array by different numbers.
- While doing dfs traversal simultaneously add node representing this element in queue which will be used in bfs.
- Use the queue created in previous steps for bfs traversal and expand every island level by level.
- if the neighboring element in grid is not marked visited then mark it visited with the same number as that of current node in visited array.
- Store distance of {current node + 1} in the distance array for neighboring unvisited element.
- else if neighboring element in grid is already marked visited with some number other than that of current node in visited array.
- return distance of current element + distance of neighboring element.
- if the neighboring element in grid is not marked visited then mark it visited with the same number as that of current node in visited array.
Below is the code for the implementation of approach:
Java
// Java code to implement the approach import java.util.*; class GFG { static int row; static int col; // A class to represent coordinates of // element in matrix static class Pair { int x; int y; int identity; Pair(int x, int y, int identity) { this.x = x; this.y = y; this.identity = identity; } } // Function to find closest distance static void closestDistance(int[][] grid) { row = grid.length; col = grid[0].length; int id = 1; Queue<Pair> q = new ArrayDeque<Pair>(); int[][] visited = new int[row][col]; // Distance array to store distance // From nearest island int[][] distance = new int[row][col]; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if (grid[i][j] == 1 && visited[i][j] == 0) { dfs(grid, visited, q, i, j, id); id++; } } } // To store minimal distance // b/w closest islands int ans = bfs(grid, visited, distance, q); System.out.println(ans); } static int[] dirx = { 0, 1, 0, -1 }; static int[] diry = { 1, 0, -1, 0 }; // Dfs function to add all island elements // In queue and marking them visited with id static void dfs(int[][] grid, int[][] visited, Queue<Pair> q, int i, int j, int id) { visited[i][j] = id; q.add(new Pair(i, j, id)); for (int idx = 0; idx < 4; idx++) { int x = i + dirx[idx]; int y = j + diry[idx]; if (isValid(x, y) && grid[x][y] == 1 && visited[x][y] == 0) { dfs(grid, visited, q, x, y, id); } } } // Bfs function to expand every island and // Maintaining distance array static int bfs(int[][] grid, int[][] visited, int[][] distance, Queue<Pair> q) { while (q.size() != 0) { Pair p = q.remove(); for (int i = 0; i < 4; i++) { int x = p.x + dirx[i]; int y = p.y + diry[i]; if (isValid(x, y) && visited[x][y] == 0) { q.add(new Pair(x, y, p.identity)); distance[x][y] = distance[p.x][p.y] + 1; visited[x][y] = p.identity; } else if (isValid(x, y) && visited[x][y] != 0 && visited[x][y] != visited[p.x][p.y]) { return distance[x][y] + distance[p.x][p.y]; } } } return -1; } // Function to check if point // Is inside grid static boolean isValid(int x, int y) { if (x < 0 || x >= row || y < 0 || y >= col) return false; return true; } // Driver Code public static void main(String[] args) { int[][] grid = { { 1, 0, 0, 0, 1 }, { 1, 1, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 1, 1, 1 } }; closestDistance(grid); }} |
2
Time Complexity: O(N2)
Auxiliary Space: O(N2)

