• 题目1091:棋盘游戏(DFS)


    题目链接:http://ac.jobdu.com/problem.php?pid=1091

    详解链接:https://github.com/zpfbuaa/JobduInCPlusPlus

    参考代码:

    //
    //  1091 棋盘游戏.cpp
    //  Jobdu
    //
    //  Created by PengFei_Zheng on 04/05/2017.
    //  Copyright © 2017 PengFei_Zheng. All rights reserved.
    //
     
    #include <stdio.h>
    #include <iostream>
    #include <algorithm>
    #include <string.h>
    #include <cstring>
    #include <cmath>
    #include <climits>
    #include <vector>
    #define MAX_SIZE 6
    //#define debug
     
    using namespace std;
     
    int n, ans = INT_MAX;
    int xStart,yStart,xEnd,yEnd;
     
    int map[MAX_SIZE][MAX_SIZE];
    bool visited[MAX_SIZE][MAX_SIZE];
     
    int change[2][4]={{-1,1,0,0},{0,0,-1,1}};
     
     
    void DFS(int x, int y, int status, int sum){
        int nextX,nextY,cost;
        if(sum < ans){
            if(x==xEnd && y==yEnd){
                ans = sum;
                return ;
            }
            for(int i = 0 ; i < 4 ; i ++){
                nextX = x + change[0][i];
                nextY = y + change[1][i];
                if(!visited[nextX][nextY] && nextX>=0 && nextX<MAX_SIZE && nextY>=0 && nextY<MAX_SIZE){
                    cost = map[nextX][nextY]*status;
                    visited[nextX][nextY]=true;
                    DFS(nextX,nextY,cost%4+1,sum+cost);//注意参数传递
                    visited[nextX][nextY]=false;
                }
            }
        }
    }
    int main(){
    #ifdef debug
        freopen("/Users/pengfei_zheng/Desktop/input.txt", "r", stdin);
    #endif
        scanf("%d",&n);
        while(n--){
            memset(map,0,sizeof(map));
            for(int i = 0 ; i < MAX_SIZE ; i++){
                for(int j = 0 ; j < MAX_SIZE ; j++){
                    scanf("%d",&map[i][j]);
                    visited[i][j]=false;
                }
            }
            ans = INT_MAX;
            scanf("%d %d %d %d",&xStart,&yStart,&xEnd,&yEnd);
            DFS(xStart,yStart,1,0);
            printf("%d
    ",ans);
        }
        return 0;
    }
    /**************************************************************
        Problem: 1091
        User: zpfbuaa
        Language: C++
        Result: Accepted
        Time:10 ms
        Memory:1520 kb
    ****************************************************************/
  • 相关阅读:
    关于这个 blog
    P6499 [COCI2016-2017#2] Burza 题解
    CF1172F Nauuo and Bug 题解
    CF1479D Odd Mineral Resource 题解
    CF1442E Black, White and Grey Tree 题解
    CF1442D Sum 题解
    CF1025D Recovering BST 题解
    CF1056E Check Transcription 题解
    CF1025F Disjoint Triangles 题解
    红包算法的PHP实现
  • 原文地址:https://www.cnblogs.com/zpfbuaa/p/6810738.html
Copyright © 2020-2023  润新知