You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

144 lines
3.4 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include <bits/stdc++.h>
using namespace std;
//*************************************************************************
/*
思路:
1到矩阵的边缘需要转向转向的方向是数组的下一个内容如果越界就是位置0
2如果前面要走的位置已经走过了就需要转向。上下左右独立封装成函数用于控制x,y的加加减减。
3如果尝试四次还没有找到出路标识进入死循环程序终止。
*/
// 上1下234
const int UP = 1, DOWN = 2, LEFT = 3, RIGHT = 4;
//顺时针
int dirSun[4] = {RIGHT, DOWN, LEFT, UP};
//逆时针
int dirNi[4] = {RIGHT, UP, LEFT, DOWN};
//矩阵
int a[10][10] = {0};
//假设矩阵为8*8
int n = 4;
//开始点
int x = 0, y = 0;
//开始时的方向
int dir = RIGHT;
//第一个位置标识上
int step = 1;
//向上走一步
bool UpStep() {
if (x - 1 >= 0 && a[x - 1][y] == 0) {
a[--x][y] = ++step;
return true;
}
return false;
}
//向下走一步
bool DownStep() {
if (x + 1 < n && a[x + 1][y] == 0) {
a[++x][y] = ++step;
return true;
}
return false;
}
//向右走一步
bool RightStep() {
if (y + 1 < n && a[x][y + 1] == 0) {
a[x][++y] = ++step;
return true;
}
return false;
}
//向左走一步
bool LeftStep() {
if (y - 1 >= 0 && a[x][y - 1] == 0) {
a[x][--y] = ++step;
return true;
}
return false;
}
//获取下一个需要尝试的方向
int NextDir(int turn) {
//需要分别讨论顺时针还是逆时针,因为数组的数组是不同的
if (turn == 1) { //顺时针
for (int i = 0; i < 4; ++i) {
if (dirSun[i] == dir) {
return dirSun[i + 1 == 4 ? 0 : i + 1];
}
}
} else { //逆时针
for (int i = 0; i < 4; ++i) {
if (dirNi[i] == dir) {
return dirNi[i + 1 == 4 ? 0 : i + 1];
}
}
}
return -1;
}
//人工智能走一步,也是核心的思路
bool autoStep(int turn) { //turn:是顺时针:1,还是逆时针:2
bool success;
int tryCount = 0;
while (tryCount < 4) {
//1、获取当前方向,决定向哪个方向走一步
switch (dir) {
case UP:
success = UpStep();
if (success) return true;
//换方向
dir = NextDir(turn);
break;
case DOWN:
success = DownStep();
if (success) return true;
//换方向
dir = NextDir(turn);
break;
case RIGHT:
success = RightStep();
if (success) return true;
//换方向
dir = NextDir(turn);
break;
case LEFT:
success = LeftStep();
if (success) return true;
//换方向
dir = NextDir(turn);
break;
}
tryCount++;
}
return false;
}
void helixMatrix() {
//出发点记录为第一步
a[x][y] = 1;
//共执行n*n次即填充满为止。
while (step < n * n) {
//模拟顺时针
bool success = autoStep(2);
if (!success) {
cout << "无法走到最后,请检查逻辑是否不正确!" << endl;
break;
}
}
//输出二维矩阵
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
cout << setw(2) << a[i][j] << " ";
}
cout << endl;
}
}
int main() {
//螺旋矩阵
helixMatrix();
return 0;
}