hdu1035

来源:互联网 发布:js水泥基怎么使用方法 编辑:程序博客网 时间:2024/05/18 13:28
模拟 + dfs;思路:首先建图,map的二维数组,用mark标记走过的地方;pi记录走到某一地方共走几步路;#include<iostream>#include<cstdio>#include<cstring>using namespace std;char map[11][11];int mark[11][11];int pi[11][11];int m, n, k, step;void dfs(int s, int e, int x, int y)//s, e 是x, y的前一个地方;{    if(x < 0 || x >= m || y < 0 || y >= n)    {        cout << pi[s][e] << " step(s) to exit" << endl;        return ;    }    if(mark[x][y])    {        cout << pi[x][y]-1 << " step(s) before a loop of "<< pi[s][e]-pi[x][y]+1 <<" step(s)" << endl;        return ;    }    if(map[x][y] == 'N')    {        mark[x][y] = 1;        step++;        pi[x][y] = step;        dfs(x, y, x-1, y);    }    else if(map[x][y] == 'S')    {        mark[x][y] = 1;        step++;        pi[x][y] = step;        dfs(x, y, x+1, y);    }    else if(map[x][y] == 'E')    {        mark[x][y] = 1;        step++;        pi[x][y] = step;        dfs(x, y, x, y+1);    }    else if(map[x][y] == 'W')    {        mark[x][y] = 1;        step++;        pi[x][y] = step;        dfs(x, y, x, y-1);    }}int main(){    while(scanf("%d%d", &m, &n) && m || n)    {        scanf("%d", &k);        step = 0;            memset(mark, 0, sizeof(mark));        for(int i = 0; i < m; i++)            cin >> map[i];        k -= 1;        pi[0][k] = 0;        dfs(0, 0, 0, k);    }}

原创粉丝点击