题目的思想不难,关键在于一些细节。先把起始格预处理出来,然后再按顺序枚举每一个起始格。每一次经过的格子标记一次,有across和down,所以用两个数组来存储标记
在输出的时候注意格式
#include<iostream> #include<string> #include<map> #include<cstdio> #include<vector> #include<algorithm> #include<assert.h> #include<cstring> using namespace std; #define _for(i, a, b) for (int i = (a); i < (b); ++i) #define _rep(i, a, b) for (int i = (a); i <= (b); ++i) struct Point{ int x, y; Point(int x = 0, int y = 0) : x(x), y(y){}; }; Point operator+(const Point A, const Point B) { return Point(A.x + B.x, A.y + B.y); }; int n, m; Point space;//空格 bool in(int x,int y){ return 0 <=x &&x < n && 0 <= y && y < m; } int vis[15][15],col[15][15],row[15][15]; vector<string> s; int main(){ int kase = 0; while(scanf("%d",&n)!=EOF&&n){ if (kase) puts(""); scanf("%d", &m); s.clear(); memset(vis, 0, sizeof(vis)); memset(col, 0, sizeof(col)); memset(row, 0, sizeof(row)); _for(i,0,n){ string str; cin >> str; s.push_back(str); } int cnt = 0; _for(i,0,n){ _for(j,0,m){ int flag = 1; if ((in(i - 1, j) && s[i - 1][j] != '*') && (in(i, j-1) && s[i][j-1] != '*')) flag = 0; if(flag&&s[i][j]!='*') vis[i][j] = ++cnt; } } // _for(i, 0, n) // { // _for(j, 0, m) // { // printf("%d ", vis[i][j]); // } // puts(""); // } printf("puzzle #%d:\n", ++kase); cout << "Across" << endl; _for(i, 0, n) { _for(j, 0, m) { int k = j, flag = 0; if (vis[i][k]) { while (!col[i][k] && in(i, k)&&s[i][k] != '*') { if (!flag) { printf("%3d.", vis[i][j]); flag++; } printf("%c", s[i][k]); col[i][k] = 1; k++; } if (flag) puts(""); } } } cout << "Down" << endl; _for(i, 0, n) { _for(j, 0, m) { int k = i, flag = 0; if (vis[i][j]) { while (!row[k][j] && in(k, j)&&s[k][j] != '*') //先考虑字符串数组是否越界,再判断*号 { if (!flag) { printf("%3d.", vis[i][j]); flag++; } printf("%c", s[k][j]); row[k][j] = 1; k++; } if (flag) puts(""); } } } } return 0; }