714260. Geek's Village and Wells

Medium

Geek's Village and Wells

Summary

The Geek's Village and Wells problem involves a village with n wells, where each well has a unique number. The goal is to find the shortest path that allows you to visit all the wells exactly once and return to the starting point. This problem can be solved using Breadth-First Search (BFS) algorithm.

Detailed Explanation

The given matrix represents the connectivity between the wells. A 1 at position [i][j] in the matrix indicates that there is a path from well i to well j, whereas a 0 means there is no path between them. The problem requires us to find the shortest possible tour that visits each well exactly once and returns to the starting point.

To solve this problem, we can use BFS algorithm. We start by choosing any well as the starting point. Then we traverse all its adjacent wells (if they exist) and mark them as visited. We repeat this process for all unvisited wells until we have visited all of them.

Here's a step-by-step breakdown of the solution:

  1. Initialize an array to store the distance from the starting point to each well.
  2. Initialize a queue with the starting point and set its distance to 0.
  3. While the queue is not empty:
    • Dequeue the next well.
    • If this well has not been visited before, mark it as visited and update its distance.
    • Enqueue all unvisited adjacent wells of the dequeued well.
  4. When all wells have been visited, return to the starting point.

Time complexity: O(n + m), where n is the number of wells and m is the number of edges in the matrix. Space complexity: O(n), for storing the distance array and the queue.

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.*;

public class GeekVillageAndWells {
    public static int findShortestTour(int[][] matrix) {
        int n = matrix.length;
        int[] dist = new int[n];
        Arrays.fill(dist, Integer.MAX_VALUE);
        dist[0] = 0;

        Queue<Integer> queue = new LinkedList<>();
        queue.add(0);

        while (!queue.isEmpty()) {
            int u = queue.poll();
            for (int v = 1; v < n; v++) {
                if (matrix[u][v] == 1 && dist[v] > dist[u] + 1) {
                    dist[v] = dist[u] + 1;
                    queue.add(v);
                }
            }
        }

        // Return to the starting point
        int tour = dist[0];
        for (int i = 1; i < n; i++) {
            if (matrix[i][0] == 1) {
                tour += dist[i];
                break;
            }
        }

        return tour;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.