今天复习了深搜和广搜然后做了作业中的一个题目。
解析:外层 for 循环:for (int i = 1; i <= n; i++),循环变量 i 从 1 递增到 n,表示要依次将数字 1 到 n 分配到数组 a 中。内层 for 循环:for (int j = 1; j <= 2; j++),内层循环控制每次寻找合适位置的步数,每次要找到两个合适的位置。s++:位置指针 s 向后移动一位。if (s > n) { s = 1; }:如果 s 超过了数组的长度 n,则将 s 重置为 1,实现循环查找。if (a[s] != 0) { j--; }:如果当前位置 s 已经被分配了值(即 a[s] 不为 0),则将内层循环的计数器 j 减 1,意味着需要重新寻找一个合适的位置。a[s] = i;:当内层循环结束后,说明已经找到了合适的位置,将当前的数字 i 存储到数组 a 的 s 位置。
#include <stdio.h>
int a[1000001], n, s;
int main() {scanf("%d", &n);for (int i = 1; i <= n; i++) {for (int j = 1; j <= 2; j++) {s++;if (s > n) {s = 1;}if (a[s] != 0) {j--;}}a[s] = i;}for (int i = 1; i <= n; i++) {printf("%d ", a[i]);}return 0;
}
解析:x[9]
和 y[9]
:这两个数组用于表示 8 个方向的偏移量,分别对应水平和垂直方向的移动。索引从 1 到 8 分别代表 8 个不同的方向。
#include <stdio.h>
#include <stdbool.h>
int x[9] = {0, 1, 0, 1, -1, 0, -1, 1, -1};
int y[9] = {0, 0, 1, 1, 0, -1, -1, -1, 1};
char str[9] = " yizhong";
char a[103][103];
bool s[102][102];
bool f(int i, int j, int m, int n, int next) {if (next >= 8) {s[i][j] = 1;return 1;}if (a[i + m][j + n] == str[next]) {if (f(i + m, j + n, m, n, next + 1)) {s[i][j] = 1;return 1;}}return 0;
}
int main() {int c[10000][2], d = 0;int n, i, j, o;scanf("%d", &n);for (i = 1; i <= n; i++) {for (j = 1; j <= n; j++) {scanf(" %c", &a[i][j]);if (a[i][j] == 'y') {c[++d][0] = i;c[d][1] = j;}}}while (d) {i = c[d][0];j = c[d][1];for (o = 1; o <= 8; o++) {if (a[i + x[o]][j + y[o]] == 'i') {if (f(i + x[o], j + y[o], x[o], y[o], 3)) {s[i][j] = 1;}}}d--;}for (i = 1; i <= n; i++) {for (j = 1; j <= n; j++) {if (s[i][j]) {printf("%c", a[i][j]);} else {printf("*");}}printf("\n");}return 0;
}