紫书 习题3-5
Posted Roni
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了紫书 习题3-5相关的知识,希望对你有一定的参考价值。
#include <iostream> #include <cstdio> #include <algorithm> using namespace std; const char inst[] = "ABLR"; const int dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; int main(void) { int t = 0; char s[5][6]; char c; while ((s[0][0] = getchar()) != ‘Z‘) { int bi = 0, bj = 0; for (int i = 0; i < 5; i ++) { for (int j = 0; j < 5; j ++) { if (!i && !j) continue; s[i][j] = getchar(); if (s[i][j] == ‘ ‘) {bi = i, bj = j;} } getchar(); } bool legal = true; while ((c = getchar()) != ‘0‘) { if (legal == false || c == ‘\n‘) continue; int k; for (k = 0; k < 4; k ++) { if (c == inst[k]) break; } if (k == 4) legal = false; else { int ni = bi+dir[k][0], nj = bj+dir[k][1]; if (0 <= ni && ni < 5 && 0 <= nj && nj < 5) { swap(s[bi][bj], s[ni][nj]); bi = ni, bj = nj; } else legal = false; } } if (++t > 1) printf("\n"); printf("Puzzle #%d:\n", t); if (legal == false) printf("This puzzle has no final configuration.\n"); else { for (int i = 0; i < 5; i ++) { for (int j = 0; j < 5; j ++) { printf("%c%c", s[i][j], j == 4 ? ‘\n‘ : ‘ ‘); } } } getchar(); } return 0; }
以上是关于紫书 习题3-5的主要内容,如果未能解决你的问题,请参考以下文章