zoukankan      html  css  js  c++  java
  • POJ

    迷宫问题
    Time Limit: 1000MS   Memory Limit: 65536K
    Total Submissions: 10936   Accepted: 6531

    Description

    定义一个二维数组: 
    int maze[5][5] = {
    
    	0, 1, 0, 0, 0,
    
    	0, 1, 0, 1, 0,
    
    	0, 0, 0, 0, 0,
    
    	0, 1, 1, 1, 0,
    
    	0, 0, 0, 1, 0,
    
    };

    它表示一个迷宫,当中的1表示墙壁。0表示能够走的路。仅仅能横着走或竖着走。不能斜着走,要求编程序找出从左上角到右下角的最短路线。

    Input

    一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。

    Output

    左上角到右下角的最短路径。格式如例子所看到的。

    Sample Input

    0 1 0 0 0
    0 1 0 1 0
    0 0 0 0 0
    0 1 1 1 0
    0 0 0 1 0

    Sample Output

    (0, 0)
    (1, 0)
    (2, 0)
    (2, 1)
    (2, 2)
    (2, 3)
    (2, 4)
    (3, 4)
    (4, 4)





    思路:DFS题。找到每一条路取最短路径


    AC代码:

    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    #include <iostream>
    #define INF 0x3fffffff
    using namespace std;
    
    int mp[5][5];
    
    int ans;
    struct node {
    	int x;
    	int y;
    }lu[30], pa[30];
    
    bool vis[8][8];
    
    const int dir[4][2] = {-1, 0, 1, 0, 0, 1, 0, -1};
    
    void dfs(int x, int y, int deep) {
    	if(x == 4 && y == 4 && deep < ans) {
    		ans = deep;
    		for(int i = 0; i < deep; i ++) {
    			pa[i].x = lu[i].x;
    			pa[i].y = lu[i].y;
    		}
    	}
    	for(int i = 0; i < 4; i ++) {
    		int tx = x + dir[i][0];
    		int ty = y + dir[i][1];
    		if(tx < 0 || tx > 4 || ty < 0 || ty > 4) continue;
    		if(mp[tx][ty] == 0 && !vis[tx][ty]) {
    			vis[tx][ty] = true;
    			lu[deep].x = tx;
    			lu[deep].y = ty;
    			dfs(tx, ty, deep + 1);
    			vis[tx][ty] = false;
    		}
    	}
    }
    
    int main() {
    	for(int i = 0; i < 5; i ++) {
    		for(int j = 0; j < 5; j ++) {
    			scanf("%d", &mp[i][j]);
    		}
    	}
    	memset(lu, 0, sizeof(lu));
    	memset(pa, 0, sizeof(pa));
    	memset(vis, false, sizeof(vis));
    	ans = INF;
    	lu[0].x = lu[0].y = 0;
    	vis[0][0] = true;
    	dfs(0, 0, 1);
    	for(int i = 0; i < ans; i ++) {
    		printf("(%d, %d)
    ", pa[i].x, pa[i].y);
    	}
    	return 0;
    }












  • 相关阅读:
    白话数字签名(番外篇)签名EXE文件(下)
    浅谈javascript函数劫持(一)
    CentOS实验五:设置主机名称
    CentOS实验四:为虚拟机配置双网卡
    CentOS实验二:添加操作员帐号
    Linux命令提示符设置
    CentOS实验三:使用安装光盘建立本地软件源
    CentOS实验一:安装CentOS Server
    mount命令
    CentOS实验六:设置命令提示符
  • 原文地址:https://www.cnblogs.com/yfceshi/p/6984694.html
Copyright © 2011-2022 走看看