1. 程式人生 > >洛谷P1605 迷宮【dfs】

洛谷P1605 迷宮【dfs】

題目 stx mes algo sign 每次 oid bar 輸出格式

題目背景

迷宮 【問題描述】

給定一個N*M方格的迷宮,迷宮裏有T處障礙,障礙處不可通過。給定起點坐標和

終點坐標,問: 每個方格最多經過1次,有多少種從起點坐標到終點坐標的方案。在迷宮

中移動有上下左右四種方式,每次只能移動一個方格。數據保證起點上沒有障礙。

輸入樣例 輸出樣例

【數據規模】

1≤N,M≤5

題目描述

輸入輸出格式

輸入格式:

【輸入】

第一行N、M和T,N為行,M為列,T為障礙總數。第二行起點坐標SX,SY,終點

坐標FX,FY。接下來T行,每行為障礙點的坐標。

輸出格式:

【輸出】

給定起點坐標和終點坐標,問每個方格最多經過1次,從起點坐標到終點坐標的方

案總數。

輸入輸出樣例

輸入樣例#1: 復制
2 2 1
1 1 2 2
1 2
輸出樣例#1: 復制
1

題意:

在一個n*m的格子中,有t個障礙物。

問從給定的起點走到給定的終點,每個格子只經過一次的走法有多少種。

思路:

dfs,走到終點方案數++

要註意,dfs之前要先把起點的vis標記為已訪問。因為這個WA了一發。

 1 //#include<bits/stdc++>
 2 #include<stdio.h>
 3 #include<iostream>
 4 #include<algorithm>
 5 #include<cstring>
 6
#include<stdlib.h> 7 #include<queue> 8 #include<map> 9 #include<stack> 10 #include<set> 11 12 #define LL long long 13 #define ull unsigned long long 14 #define inf 0x3f3f3f3f 15 16 using namespace std; 17 18 int n, m, t; 19 bool barrier[10][10]; 20 bool vis[10][10]; 21
int stx, sty, edx, edy; 22 int dx[4] = {0, 0, -1, 1}; 23 int dy[4] = {1, -1, 0, 0}; 24 int ans = 0; 25 26 bool check(int x, int y) 27 { 28 return(x > 0 && y > 0 && x <= n && y <= m && !barrier[x][y] && !vis[x][y]); 29 } 30 31 void dfs(int x, int y) 32 { 33 if(x == edx && y == edy){ 34 ans++; 35 return; 36 } 37 int cnt = 0; 38 for(int i = 0; i < 4; i++){ 39 if(check(x + dx[i], y + dy[i])){ 40 vis[x + dx[i]][y + dy[i]] = true; 41 dfs(x + dx[i], y + dy[i]); 42 vis[x + dx[i]][y + dy[i]] = false; 43 } 44 } 45 return; 46 } 47 48 int main() 49 { 50 scanf("%d%d%d", &n, &m, &t); 51 scanf("%d%d", &stx, &sty); 52 scanf("%d%d", &edx, &edy); 53 for(int i = 0; i < t; i++){ 54 int x, y; 55 scanf("%d%d", &x, &y); 56 barrier[x][y] = true; 57 } 58 vis[stx][sty] = true; 59 dfs(stx, sty); 60 printf("%d\n", ans); 61 62 return 0; 63 }

洛谷P1605 迷宮【dfs】