L1-5 回形针,yyds! (15分)
回形针,是一种回型的针。(废话 输入格式:
一行字符串,长度不超过104。 输出格式:
将输入的字符串以螺旋状输出,使得输出呈现一个正方形(行数=每行字符数),要求该正方形在大小足以容纳该字符串的前提下尽可能小。若按指定方式填充后该正方形内有空缺,则空缺部分以空格填补。输出从左上角开始向右行进,遇到拐角即右转(示意图:回形针.png)。 输入样例:
This is a test case.
输出样例:
This casei .s t set a
思路:直接利用简单搜索解决,key point 在与一直要向一个方向搜索直到违法的情况(越界,已经搜过了)
#include<bits/stdc++.h> using namespace std; const int N = 103; char a[N][N]; string s; int vis[N][N]; int n; int dx[] = { 0, 1, 0, -1}, dy[] = { 1, 0, -1, 0}; int cnt = 0; int len; int x3; int to = 0; bool judge(int x1, int y1) { if(x1 < 1 || y1 < 1 || x1 > x3 || y1 > x3 || vis[x1][y1] == true) return false; return true; } void dfs(int x, int y) { vis[x][y] = 1; a[x][y] = s[cnt ++]; if(cnt == len) return; int x1 = x + dx[to], y1 = y + dy[to]; if(judge(x1, y1) == false) { to ++; // 改变方向 to %= 4; } x1 = x + dx[to]; y1 = y + dy[to]; dfs(x1, y1); } int main() { getline(cin, s); len = s.size(); x3 = sqrt(len); if(x3 * x3 < len) x3 ++; //cout << x3 << endl; for(int i = 1; i <= x3; i++) for(int j = 1; j <= x3; j++) a[i][j] = ; dfs(1, 1); for(int i = 1; i <= x3; i++) { for(int j = 1; j <= x3; j++) { printf("%c", a[i][j]); } cout << endl; } return 0; }