文章

5

粉丝

100

获赞

2

访问

46.1k

头像
DFS遍历,未通过,卡在5x5棋盘
P1628 上海交通大学2018年机试题
发布于2021年2月28日 23:16
阅读数 8.7k

#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
int flag[10][10];
int N, M, total, res;
int locX[4] = {1,-1,0,0};
int locY[4] = {0,0,1,-1};

void DFS(int n, int m, int cnt){
    if(res == 1) return;
    if(cnt == total){
        res = 1;
        return;
    }
    flag[n][m]++;
    for(int i=0; i<4; i++){
        int nowX = n+locX[i];
        int nowY = m+locY[i];
        if(nowX>=0 && nowX<N && nowY>=0 && nowY<M && flag[nowX][nowY]==0){
            DFS(nowX, nowY, cnt+1);
        }
    }
    flag[n][m] = 0;
}

int main(){
   &nb...

登录查看完整内容


登录后发布评论

3 条评论
admin SVIP
2021年3月1日 22:54

在你的代码基础上改了一下,有的数据比较特殊

#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
int flag[15][15];
int N, M, total, res;
int locX[4] = {1,-1,0,0};
int locY[4] = {0,0,1,-1};

void DFS(int n, int m, int cnt){
    if(res == 1) return;
    if(cnt == total){
        if ((n == 0 && m == 1) || (n == 1 && m == 0))
            res = 1;
        else
            return;
    }
    
    for(int i=0; i<4; i++){
        int nowX = n+locX[i];
        int nowY = m+locY[i];
        if(nowX>=0 && nowX<N && nowY>=0 && nowY<M && flag[nowX][nowY]==0){
            flag[nowX][nowY] = 1;
            DFS(nowX, nowY, cnt+1);
            flag[nowX][nowY] = 0;
        }
    }
    
}

int main(){
    while(cin>>N>>M){
        if (N==1&&M==1) {
            cout<<"Y"<<endl;
            continue;
        }
        if ((N==1&&M==2)||(N==2&&M==1)) {
            cout<<"N"<<endl;
            continue;
        }

        res = 0;
        total = N*M;
        memset(flag, 0, sizeof(flag));
        flag[0][0] = 1;
        DFS(0, 0, 1);
        if(res == 1) cout<<"Y"<<endl;
        else cout<<"N"<<endl;
    }
}

 

赞(0)
admin SVIP
2021年3月1日 12:35

dfs回溯的时候flag需要重置

赞(0)

hrcarryu : 回复 admin: 代码复制错了,复制的旧版本,重置后其实也通过不了。。

2021年3月1日 13:17