跳到正文

题解

【NOIP2017】棋盘

Mindulle约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 3 分钟
获赞
1

版本

  1. v1当前

稍微复杂一点的搜索题。

总体来说,思维难度不算很高。属于下位绿。

具体思路见代码注释。

只用记忆化即可,稍微一点剪枝(甚至不用,我没试过)就过了。

C++
#include<bits/stdc++.h>
using namespace std;
//dis:记忆化数组
//dx,dy:方向数组
int m,n,maze[101][101],dis[101][101],dx[4]={-1,1,0,0},dy[4]={0,0,-1,1};
void dfs(int x,int y,int step,bool f){ //x,y:当前坐标 step:步数 f:有没有用过魔法
    if(step>=dis[x][y]) return; //如果当前步数比最优步数还多,直接跳出
    dis[x][y]=step; //记忆化数组保存当前步数
    if(x==m&&y==m) return; //如果到达终点就跳出
    for(int i=0;i<4;i++){ //枚举4个方向
        int tx=x+dx[i],ty=y+dy[i]; //可能到达位置的坐标存储下来
        if(tx>0&&tx<=m&&ty>0&&ty<=m ){ //如果在迷宫范围内
            //不能是-1,而且颜色相同时
            if(maze[tx][ty]>-1&&maze[x][y]==maze[tx][ty] ) dfs(tx,ty,step,0);
            //颜色不同,就要花费一个金币,所以step+1
            else if(maze[tx][ty]>-1&&maze[x][y]!=maze[tx][ty]) dfs(tx,ty,step+1,0);
            //最后考虑一下用不用魔法,用魔法的前提是之前没有用过
            else if(maze[tx][ty]==-1&&!f){
                maze[tx][ty]=maze[x][y];
                dfs(tx,ty,step+2,1);
                maze[tx][ty]=-1;
            }
        }
    }
}
int main(){
    memset(maze,-1,sizeof(maze)); //这里一定要初始化
    memset(dis,0x3f,sizeof(dis)); //这里也是
    cin>>m>>n; //读入
    int sx,sy,c;
    while(n--){
        cin>>sx>>sy>>c;
        maze[sx][sy]=c;
    }
    dfs(1,1,0,0); //dfs!
    //输出
    if(dis[m][m]!=0x3f3f3f3f) cout<<dis[m][m];
    else cout<<-1;//注意特判
    return 0;
}
原文