题目链接:http://acm.ecnu.edu.cn/problem/3260/
仍然是搜索,暴力,每尝试一个方向,就把另外的几个方向全部堵死(造墙),如果搜到终点时步数大于等于k,则停止一切搜索,输出地图。
尝试四个方向的时候不知道具体有哪几个方向可以通行,就先把几个方向保留下来,根据方向的个数来判断堵死哪几个方向。
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int dx[4] = {0,1,0,-1};
const int dy[4] = {1,0,-1,0};
struct node
{
int x, y;
};
char c[10][10];
int n, m;
int tx, ty, k;
bool flag = false;
void dfs(int x, int y, int step, int lx, int ly)
{
node s[3];
int cnt = 0;
for (int i=0; i<4; i++)
{
int nx = x + dx[i];
int ny = y + dy[i];
if (nx<1 || nx>n || ny<1 || ny>m ||nx==lx&&ny==ly || c[nx][ny]=='*')
continue;
if (nx == tx && ny == ty)
{
if (step + 1 >= k)
flag = true;
return;
}
s[cnt].x = nx;
s[cnt++].y = ny;
}
int x1, x2, x3, y1, y2, y3;
if (cnt == 3)
{
x1 = s[0].x; y1 = s[0].y;
x2 = s[1].x; y2 = s[1].y;
x3 = s[2].x; y3 = s[2].y;
c[x1][y1] = c[x2][y2] = '*';
c[x3][y3] = '.';
dfs(x3,y3,step+1,x,y);
if (flag) return;
c[x1][y1] = c[x3][y3] = '*';
c[x2][y2] = '.';
dfs(x2,y2,step+1,x,y);
if (flag) return;
c[x2][y2] = c[x3][y3] = '*';
c[x1][y1] = '.';
dfs(x1,y1,step+1,x,y);
if (flag) return;
c[x2][y2] = c[x3][y3] = '.';
}
else if (cnt == 2)
{
x1 = s[0].x; y1 = s[0].y;
x2 = s[1].x; y2 = s[1].y;
c[x1][y1] = '*';
c[x2][y2] = '.';
dfs(x2,y2,step+1,x,y);
if (flag) return;
c[x2][y2] = '*';
c[x1][y1] = '.';
dfs(x1,y1,step+1,x,y);
if (flag) return;
c[x2][y2] = '.';
}
else if (cnt == 1)
{
x1 = s[0].x; y1 = s[0].y;
dfs(x1,y1,step+1,x,y);
}
}
int main()
{
cin >> n >> m;
cin >> tx >> ty >> k;
memset(c, '.', sizeof(c));
dfs(1,1,0,0,0);
for (int i=1; i<=n; i++)
{
for (int j=1; j<=m; j++)
cout << c[i][j];
cout << endl;
}
return 0;
}