Medium csharp

BFS shortest path in grid #75

Problem

3x3 grid BFS from (0,0) to (2,2); print path length.

Hints
  • Queue + visited matrix

Your solution

TestStatusDetails
Ready — edit the code above and click Run or Submit.

Solution

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        int[][] g = { new[]{0,0,0}, new[]{1,0,0}, new[]{0,0,0} };
        var q = new Queue<(int r,int c,int d)>();
        q.Enqueue((0,0,1));
        var vis = new bool[3,3]; vis[0,0] = true;
        int[] dr = {0,0,1,-1}, dc = {1,-1,0,0};
        while (q.Count > 0) {
            var (r,c,d) = q.Dequeue();
            if (r == 2 && c == 2) { Console.WriteLine(d); return; }
            for (int k = 0; k < 4; k++) {
                int nr = r + dr[k], nc = c + dc[k];
                if (nr>=0&&nr<3&&nc>=0&&nc<3&&!vis[nr,nc]&&g[nr][nc]==0) {
                    vis[nr,nc]=true; q.Enqueue((nr,nc,d+1));
                }
            }
        }
    }
}

Try solving on your own first, then reveal the official answer.

Explanation

BFS finds shortest path in unweighted grid.

Discussion

0

Sign in to join the discussion.

No discussions yet — ask the first question!

Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details