3x3 grid BFS from (0,0) to (2,2); print path length.
| Test | Status | Details |
|---|
Ready — edit the code above and click Run or Submit.
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.
BFS finds shortest path in unweighted grid.