Topic:
Basic idea:
This is a deep search problem, however, you can see the answer to the question: the number of cities, so can not use a full traversal, can not meet the complexity of time requirements. So the data needs to be preprocessed, that is, to convert the map into a linked list, the map should be only 0, 1 of the value, indicating that there is a path or no path. However, in order to save some memory (although not necessary), so map multiplexing. If the current node I is connected to another node J, the node J is placed in the map. The No. 0 element holds the current access to the first node (starting from 1, which is useful when searching backwards), followed by a node adjacent to it, and finally ending with-1.
Code:
#include <stdio.h> #include <string.h>int main () {const int N = 10;int map[n][n];int stack[n];bool visited[n]; int N,a,b;int begin;int i,j;while (scanf ("%d%d%d", &n, &a, &b)! = EOF) {for (i = 0; i < n; ++i) {for (j = 0; j < n; ++J) {scanf ("%d", &map[i][j]);}} for (i = 0; i < n; ++i) {int index = 0;map[i][0] = 1;for (j = 0; J < N; ++j) {if (Map[i][j] && i! = j) Map[i][++in DEX] = j;//record the point}map[i][++index] = -1;//-1 end}//Deep Search memset (visited, 0, N * sizeof (BOOL)); int top = -1;int ans = 0;stack[++t OP] = a;//a into stack visited[a] = true;while (Top >-1)//Stack not empty {Begin = stack[top];//take stack top element for (i = map[begin][0]; Map[begin][i]! =- 1; ++i) {if (map[begin][i]! = b &&!visited[map[begin][i]])//not visited {Stack[++top] = Map[begin][i];visited[map[begin] [i]] = true;map[begin][0] = i + 1;break;} if (map[begin][i] = = b) ++ans;} if (map[begin][i] = = 1)//The point of all the paths have gone through, the stack {--top;}} End for whileprintf ("%d\n", ans);} return 0;}
Test results:
Huawei Machine Test-all roads to Rome