UVA - 705 Slash Maze

来源:互联网 发布:ubc专业 知乎 编辑:程序博客网 时间:2024/06/06 15:41

题目大意:给出一个用 / 和 \ 表示的矩阵,求所围成的封闭的环的个数和最大长度。

解题思路:一开始就想把 / \ 放大化成题目中的图,然而发现格子是斜的貌似不太好弄,百度题解也是放大然后用 1 和 0 表示,很巧妙。

\ / 10 01 01 10

化完写在纸上数环和长度发现自己都走错,斜着走的时候需要判断,并不是所有情况都可以走,接着打了一个上午被特殊判断弄懵逼。然后直接放大 3 倍,就只要上下左右四个方向走了,简单一些。

\ / 100 001 010 010 001 100
#include<iostream>#include<cstdio>#include<cstdlib>#include<cstring>#include<cmath>#include<algorithm>using namespace std;int map[300][300];int dd[4][2] = {{-1,0},{1,0},{0,-1},{0,1}};int tot = 0, w, h, cnt, ans, tag, tmp;void dfs(int r, int c) {    map[r][c] = 1;    int x, y;    for (int i = 0; i < 4; i++) {        x = r + dd[i][0];        y = c + dd[i][1];        if (x < 0 || x >= 3*h || y < 0 || y >= 3*w) tag = 0;        else if (map[x][y] == 0) {                tmp++;                dfs(x, y);            }        }}int main() {    while (scanf("%d%d", &w, &h) && w+h) {        memset(map, 0, sizeof(map));        for (int i = 0; i < h; i++) {            string str;            cin >> str;            for (int j = 0; j < w; j++) {                if (str[j] == '/') {                    map[i*3][j*3+2] = 1;                    map[i*3+1][j*3+1] = 1;                    map[i*3+2][j*3] = 1;                }                else {                    map[i*3][j*3] = 1;                    map[i*3+1][j*3+1] = 1;                    map[i*3+2][j*3+2] = 1;                }            }        }        ans = cnt = 0;        for (int i = 0; i < 3*h; i++)            for (int j = 0; j < 3*w; j++)                if (map[i][j] == 0) {                    tag = 1;                    tmp = 1;                    dfs(i, j);                    if (tag) {                        cnt++;                        if (tmp > ans) ans = tmp;                    }                }        printf("Maze #%d:\n", ++tot);        if (cnt == 0) printf("There are no cycles.\n\n");        else printf("%d Cycles; the longest has length %d.\n\n", cnt, ans/3);    }return 0;}
0 0
原创粉丝点击