应用场景
在迷宫、棋盘等问题中,经常需要使用方向数组。
一般的“寻路”类问题都可以使用方向数组来编程求解。
示例
#include <iostream> using namespace std; int dirx[4] = {-1, 0 , 1, 0}; //x direct int diry[4] = {0 , 1, 0, -1}; //y direct int main() { int a, b; cin >> a >> b; for (int i = 0; i < 4; i++) { int x = a + dirx[i]; int y = b + diry[i]; cout << x << " " << y << endl; } return 0; }
【例题】简易迷宫
输入:
6 6 ....## ..#.## ..#S## .T#... .##... ......
输出:7
代码实现(C++)
#include <iostream> #include <queue> using namespace std; struct node { int x, y, step; }; int dir[4][2] = {0, 1, 1, 0, 0, -1, -1, 0}; //x direct int n, m, sx, sy; char mmap[105][105]; int main() { cin >> n >> m; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { cin >> mmap[i][j]; if (mmap[i][j] == 'S') { sx = i, sy =j; } } } queue<node> que; que.push((node){sx, sy, 0}); while (!que.empty()) { node temp = que.front(); que.pop(); for (int i = 0; i < 4; i++) { int x = temp.x + dir[i][0]; int y = temp.y + dir[i][1]; if (mmap[x][y] == 'T') { cout << temp.step + 1 << endl; return 0; } if (mmap[x][y] == '.') { que.push((node){x, y ,temp.step + 1}): mmap[x][y] = 0; } } } cout << -1 << endl; return 0; }