所需函数、数组
const int maxn = (); // 根据实际情况
char g[maxn][maxn];
bool st[maxn][maxn];
int n, m;
struct node{
int x, y;
};
inline bool isLegal(int x, int y) { // 判断坐标是否合法
if (x < 0 || x >= n) return false;
if (y < 0 || y >= m) return false;
// 根据实际情况
if (g[x][y] == () || st[x][y]) return false;
return true;
}
常用坐标偏移数组
上、下、左、右
const int dx[] = {-1, 0, 1, 0};
const int dy[] = {0, 1, 0, -1};
八个方向
const int dx[] = {-1, 0, 1, -1, 1, -1, 0, 1};
const int dy[] = {-1, -1, -1, 0, 0, 1, 1, 1};
日字
const int dx[] = {-1, 1, -2, 2, -2, 2, -1, 1};
const int dy[] = {-2, -2, -1, -1, 1, 1, 2, 2};
DFS模版
bool dfs(int x, int y) { // 判断是否能到终点
if (x == ex && y == ey) return true;
for(int i = 0; i < 4; i++) { // 看情况设置条件
int xx = x + dx[i], yy = y + dy[i];
if (!isLegal(xx, yy)) continue;
st[xx][yy] = true;
if (dfs(xx, yy)) return true;
}return false;
}
BFS模版
bool bfs(int sx, int sy, int ex, int ey) {
queue<node> q;
q.push({sx, sy});
while (!q.empty()) {
node t = q.front();
q.pop();
if (t.x == ex && t.y == ey) return true;
for(int i = 0; i < 4; i++) {
int x = t.x + dx[i], y = t.y + dy[i];
if (!isLegal(x, y)) continue;
st[x][y] = true;
q.push({x, y});
}
}return false;
}