除了第一个点,其他全部RE(感觉是递归出了问题导致栈溢出)
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
int map[1001][1001], book[1001][1001], n, m, sx, sy, fx, fy;
int nx[4] = {1, -1, 0, 0}, ny[4] = {0, 0, -1, 1}, min_cost = 1000000000;
struct queue { int x, y; };
void DFS(int x, int y, int magic, int cost)
{
if (x == fx && y == fy)
{
if (cost < min_cost) min_cost = cost;
return ;
}
for (int i = 0; i < 4; i++)
{
int xx = x + nx[i], yy = y + ny[i];
if (xx <= n && yy <= n && xx >= 1 && yy >= 1 && map[xx][yy] != 0 && book[xx][yy] != 1)
{
if (map[xx][yy] != map[x][y]) cost += 1;
if (cost > min_cost) return ;
book[xx][yy] = 1;
DFS(xx, yy, magic, cost);
if (map[xx][yy] != map[x][y]) cost -= 1;
book[xx][yy] = 0;
}
if (magic == 0)
{
cost += 2;
if (cost > min_cost) return ;
map[xx][yy] = map[x][y];
book[xx][yy] = 1;
DFS(xx, yy, 1, cost);
map[xx][yy] = 0;
cost -= 2;
book[xx][yy] = 0;
}
if (magic == 1)
{
map[x][y] = 0;
magic = 0;
}
}
return ;
}
int main()
{
cin >> n >> m;
sx = 1; sy = 1; fx = n; fy = n;
for (int i = 0; i < m; i++)
{
int x, y, z;
cin >> x >> y >> z;
map[x][y] = z + 1;
}
DFS(sx, sy, 0, 0);
cout << ((min_cost == 1000000000) ? -1 : min_cost);
return 0;
}