• [POJ] 2488.A Knight's Journey


    题目传送门
    题意:日字走,一次走完给定的p*q棋盘,记录步骤,输出
    思路:dfs + 回溯

    #include <algorithm>
    #include <bitset>
    #include <cstdio>
    #include <cstring>
    #include <fstream>
    #include <iostream>
    #include <string>
    #include <vector>
    using namespace std;
    int p, q;
    int dy[8] = {-2, -2, -1, -1, 1, 1, 2, 2};
    int dx[8] = {-1, 1, -2, 2, -2, 2, -1, 1};
    int chess[26][26];
    bool flag;
    struct step {
      int x;
      char y;
    } path[26];
    
    void dfs(int x, int y, int counts) {
      path[counts].x = x;
      path[counts].y = y + 'A' - 1;
      int x1, y1;
      if (counts == p * q) {
        flag = true;
        for (int i = 1; i <= p * q; i++) printf("%c%d", path[i].y, path[i].x);
        printf("
    ");
      }
      if (flag) return;
    
      for (int i = 0; i < 8; i++) {
        x1 = x + dx[i];
        y1 = y + dy[i];
    
        if (x1 > 0 && x1 <= p && y1 > 0 && y1 <= q && !chess[x1][y1]) {
          chess[x1][y1] = 1;
          dfs(x1, y1, counts + 1);
          chess[x1][y1] = 0;
        }
      }
    }
    
    int main() {
      int n;
      scanf("%d", &n);
      int c = 1;
      while (n--) {
        memset(chess, 0, sizeof(chess));
        flag = false;
        scanf("%d%d", &p, &q);
        printf("Scenario #%d:
    ", c++);
        chess[1][1] = 1;
        dfs(1, 1, 1);
        if (!flag) printf("impossible
    ");
        printf("
    ");
      }
      system("pause");
      return 0;
    }
  • 相关阅读:
    return跳转 和 goto跳转
    continue跳转
    break跳转
    循环的嵌套,以for循环为例
    for“列表”型循环
    do while“直到”型循环
    while“当”型循环
    选择结构 switch
    Tomcat和Servlet简析
    并发事务和隔离级别
  • 原文地址:https://www.cnblogs.com/ruoh3kou/p/9893454.html
Copyright © 2020-2023  润新知