JSK-DFS-走迷宫

题目

dfs水题,贴上dfs模板

void dfs(int deep) {
    if (到达边界) {
      // 做一些处理后返回
    } else {
        for(所有可能的选择) {
            dfs(deep + 1);
        }
    }
}

代码框架:

// 对坐标为(x, y)的点进行搜索
void dfs(int x, int y) {
    if (x,y) 是终点 {
        方案数增加
        return;
    }
    标记(x, y)已经访问
    for (x, y) 能到达的格子(tx, ty) {
        if (tx, ty) 没有访问 {
            dfs(tx, ty);
        }
    }
    取消(x, y)访问标记
}

遍历方案:

int x, y;
int xx[8] = {1, 0, -1, 0}; //横向位移
int yy[8] = {0, 1, 0, -1}; //纵向位移

for (int i = 0; i < 4; ++i) {
    int tx = x + xx[i]; //计算能到达的点横坐标
    int ty = y + yy[i]; //计算能到达的点纵坐标
    //做一些处理
}

AC警告:

#include<bits/stdc++.h>
using namespace std;
char amap[12][12];

int sx, sy, ans, n, m;
int to[4][2] = {{1,0},{0,1},{-1,0},{0,-1}};
void dfs(int x, int y)
{
	if(amap[x][y] == 'T'){
		ans++;
		return ;
	}
	amap[x][y] = '#';
	for(int i = 0; i < 4; i++){
		if((x + to[i][0] >= 0) && (y + to[i][1] >= 0) && (x + to[i][0] < n) && (y + to[i][1] < m) && (amap[x + to[i][0]][y + to[i][1]] != '#'))
			dfs(x + to[i][0] , y + to[i][1]);
	}
	amap[x][y] = '.';
	return ;
}
int main()
{
    cin>>n>>m;
	getchar();
	for(int i = 0; i < n; ++i){
		for(int j = 0; j < m; ++j){
			char c = getchar();
			if(c == 'S'){
				sx = i;
				sy = j;
			}
			amap[i][j] = c;
		}
		getchar();
	}
	ans = 0;
	dfs(sx,sy);
	cout<<ans<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/giggle66/article/details/90203819