using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BFS { class Program { private const int MAXX = 100; private const int MAXY = 100; private static int m_dx = -1; private static int m_dy = -1; private static Queue<Point> m_Q; static void Main(string[] args) { int xlength = 4; int ylength = 4; Point[][] g = new Point[xlength][]; int[][] map = new int[][] {new int[] {0, 0, 0, 0}, new int[] {0, 1, 0, 1}, new int[] {0, 0, 0, 1}, new int[] {1, 2, 1, 1}}; Inist(g, xlength, ylength); BFS(g, new Point() {X = 0, Y = 0}, xlength, ylength, map); var end = g[m_dx][m_dy].Distance; } public static void Inist(Point[][] g,int xlength,int ylenth) { for (int i = 0; i <xlength; i++) { g[i] = new Point[ylenth]; } m_Q = new Queue<Point>(); } public static void BFS(Point[][] g, Point s, int xlength, int ylength,int[][] map) { for (int i = 0; i < xlength; i++) { for (int j = 0; j < ylength; j++) { var type = map[i][j]; g[i][j] = new Point() { Color = 0, Distance = int.MaxValue, Parent = null, X = i, Y = j, type = type }; if(type==2) { m_dx = i; m_dy = j; g[i][j].type = 0; } } } g[s.X][s.Y].Color = 1; g[s.X][s.Y].Distance = 0; g[s.X][s.Y].Parent = null; m_Q.Enqueue(g[s.X][s.Y]); while (m_Q.Count!=0) { Point u = m_Q.Dequeue(); var adjList = GenerAdjustList(g, u, xlength,ylength); for (int i = 0; i < adjList.Count; i++) { var v = adjList[i]; if(v.Color==0&&v.type==0) { v.Color = 1; v.Distance = u.Distance + 1; v.Parent = u; m_Q.Enqueue(v); } } u.Color = 2; } } private static List<Point> GenerAdjustList(Point[][] points, Point point, int xlength, int ylength) { var list = new List<Point>(); if(point.X+1<xlength) { list.Add(points[point.X+1][point.Y]); } if(point.X-1>0) { list.Add(points[point.X - 1][point.Y]); } if (point.Y + 1 < ylength) { list.Add(points[point.X][point.Y + 1]); } if (point.Y - 1 > 0) { list.Add(points[point.X][point.Y - 1]); } return list; } } public class Point { public int X; public int Y; public int Color; public int type; public int Distance; public Point Parent; } }