之前在網上看到的多是Java 但是我沒學過Java..... 找了一篇C的,調了很久很久很久.......
假設城堡地面是 n x n 個方格。【如圖1.png】所示。
按習俗,騎士要從西北角走到東南角。
可以橫向或縱向移動,但不能斜着走,也不能跳躍。
每走到一個新方格,就要向正北方和正西方各射一箭。
(城堡的西牆和北牆內各有 n 個靶子)
同一個方格只允許經過一次。但不必走完所有的方格。
如果只給出靶子上箭的數目,你能推斷出騎士的行走路線嗎?
有時是可以的,比如圖1.png中的例子。
本題的要求就是已知箭靶數字,求騎士的行走路徑(測試數據保證路徑唯一)
輸入:
第一行一個整數N(0<N<20),表示地面有 N x N 個方格
第二行N個整數,空格分開,表示北邊的箭靶上的數字(自西向東)
第三行N個整數,空格分開,表示西邊的箭靶上的數字(自北向南)
輸出:
一行若干個整數,表示騎士路徑。
爲了方便表示,我們約定每個小格子用一個數字代表,從西北角開始編號: 0,1,2,3....
比如,圖1.png中的方塊編號爲:
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
示例:
用戶輸入:
4
2 4 3 4
4 3 3 3
程序應該輸出:
0 4 5 1 2 3 7 11 10 9 13 14 15
代碼如下:
- #include "stdafx.h"
- #include <iostream>
- using namespace std;
- int N;
- const int max = 20;
- int west[max];
- int north[max];
- int pic[max][max];
- int iv[400];
- int dicx[] = { 1,-1,0,0 };
- int dicy[] = { 0,0,1,-1 };
- int ans[400];
- int num;
- bool ok = false;
- bool isin(int x,int y)
- {
- if (x < N && x >= 0 && y < N && y >= 0)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- bool J()
- {
- for (int i = 0; i < N; i++)
- {
- if (north[i] != 0)
- return false;
- }
- for (int i = 0; i < N; i++)
- {
- if (west[i] != 0)
- return false;
- }
- return true;
- }
- bool isr(int x, int y)
- {
- if (west[y] >= 0 && north[x] >= 0)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- void dfs(int x,int y,int l)
- {
- if (pic[y][x] == N * N - 1 )//終止條件
- {
- if (J())
- {
- ans[l] = pic[y][x];
- ok = true;
- num = l;
- return;
- }
- else
- {
- return;
- }
- }
- if (isin(x, y) && !(bool)iv[pic[y][x]] && isr(x,y))//判斷當前位置是否符合條件 1.在圖內 2.未經過 3.可以經過
- {
- iv[pic[y][x]] = 1;//嘗試
- ans[l] = pic[y][x];
- for (int i = 0; i < 4; i++)//判斷當前位置能否繼續求解
- {
- int y_tem = y + dicy[i];
- int x_tem = x + dicx[i];
- if (isin(x_tem, y_tem) && !(bool)iv[pic[y_tem][x_tem]] && north[x_tem] - 1 >=0 && west[y_tem] - 1 >= 0)
- {
- north[x_tem] = north[x_tem] - 1;//嘗試
- west[y_tem] = west[y_tem] - 1;
- dfs(x_tem, y_tem, l + 1);
- if (ok) return;
- north[x_tem] = north[x_tem] + 1;//撤銷
- west[y_tem] = west[y_tem] + 1;
- }
- }
- iv[pic[y][x]] = 0;//撤銷
- return;
- }
- else
- return;
- }
- int main()
- {
- cin >> N;
- for (int i = 0; i < N; i++)
- {
- cin >> north[i];
- }
- for (int i = 0; i < N; i++)
- {
- cin >> west[i];
- }
- int k = 0;
- for (int i = 0; i < N; i++)
- {
- for (int n = 0; n < N; n++)
- {
- pic[i][n] = k;
- k++;
- }
- }
- for (int i = 0;i < 400; i++)
- {
- iv[i] = 0;
- }
- west[0]--;
- north[0]--;
- dfs(0, 0, 0);
- for (int i = 0; i<= num; i++)
- {
- cout << ans[i] << " ";
- }
- system("pause");
- return 0;
- }