int n, m; int g[N][N]; //用来存迷宫具体的数值 int d[N][N]; //用来存各点到起点的距离 int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1}; //方向偏移量 pair<int, int> q[N*N]; //用数组来模拟队列, 数组的类型是int型二元组存坐标
classSolution { public: intshortestPathBinaryMatrix(vector<vector<int>>& grid){ int n = grid.size(); if (grid[0][0] == 1 || n == 0) return-1; // 定义8个方向 int dx[8] = {-1,0,1,0,-1,-1,1,1}; int dy[8] = {0,1,0,-1,1,-1,-1,1}; queue<pair<int,int >>q; q.push({0,0}); int path = 1; // 答案初始值是1 while (q.size()) { int size = q.size(); while (size--) { auto t = q.front(); q.pop(); //扫到终点直接返回即可 if (t.first == n - 1 && t.second == n - 1) return path; for (int i = 0; i < 8; i++) { int a = t.first + dx[i], b = t.second + dy[i]; if (a >= 0 && a < n && b >= 0 && b < n && grid[a][b] == 0 ) { q.push({a, b}); grid[a][b] = 1; // 访问过的标记为1