#include <iostream>
#include <cstdio>
using namespace std;
int n, m;
int mn = 0x7fffff;
int dx[] = {0, 1, 0, -1};
int dy[] = {1, 0, -1, 0};
bool vis[1010][1010];
int money[1010][1010];
int a[1010][1010];
void dfs(int x, int y, int cost, int color)
{
if(x == n && y == n)
{
mn = min(cost, mn);
return ;
}
for(int i = 0; i < 4; i ++)
{
int nx = x + dx[i], ny = y + dy[i];
if(nx > n || nx <= 0 || ny > n || ny <= 0)
{
continue;
}
if(vis[nx][ny])
{
continue;
}
if(a[nx][ny] != 0 || a[x][y] != 0)
{
if(a[nx][ny] == 0)
{
if(cost + 2 < money[nx][ny])
{
vis[nx][ny] = true;
money[nx][ny] = cost + 2;
dfs(nx, ny, cost + 2, color);
vis[nx][ny] = false;
}
}
else
{
if(color == a[nx][ny] && cost < money[nx][ny])
{
vis[nx][ny] = true;
money[nx][ny] = cost;
dfs(nx, ny, cost, color);
vis[nx][ny] = false;
}
else if(cost + 1 < mn && cost + 1 < money[nx][ny])
{
vis[nx][ny] = true;
money[nx][ny] = cost + 1;
dfs(nx, ny, cost + 1, a[nx][ny]);
vis[nx][ny] = false;
}
}
}
}
}
int main()
{
scanf("%d%d", &n, &m);
for(int i = 1; i <= n; i ++)
{
for(int j = 1; j <= n; j ++)
{
money[i][j] = 0x7fffff;
}
}
for(int i = 1; i <= m; i ++)
{
int x, y, w;
scanf("%d%d%d", &x, &y, &w);
a[x][y] = w + 1;
}
vis[1][1] = false;
dfs(1, 1, 0, a[1][1]);
printf(mn == 0x7fffff ? "-1" : "%d\n", mn);
return 0;
}
ybt1416-NOIP2017普及组第三题真题
最新推荐文章于 2024-05-01 19:35:02 发布