ã¯ããã«
ã¿ããªããããï¼ nikkieã§ãã
ä»åã¯è¦ææèã®ããåéã«åãçµã¿ã¾ãã
ç§ãããããï¼
ç®æ¬¡
- ã¯ããã«
- ç®æ¬¡
- ãªãã¨ãªãè¦ææè
- ãåé¡è§£æ±ºåãéããï¼ã¢ã«ã´ãªãºã ã¨ãã¼ã¿æ§é ã
- Pythonã§åçµï¼å帰ã使ã£ãDFS
- é¢é£ãªã½ã¼ã¹
- çµããã«
ãªãã¨ãªãè¦ææè
å®ã¯ç«¶æããã°ã©ãã³ã°ï¼AtCoderã®ABCï¼ã1æ¡åæ°ãã£ããã¨ãããã¾ãã
Aã»Båé¡ã¯è§£ããã®ã§ãããCåé¡ããå
ãé£ããã£ãã§ãã
ããã¯ç«¶æããã°ã©ãã³ã°ã®åºæ¬ã身ã«ã¤ãã¦ããªãããã ãããªã¨èãã¦ãã¾ããã
ãã®1ã¤ãã°ã©ãã®æ¢ç´¢ã§ãã
ã°ã©ãã®æ¢ç´¢ã¢ã«ã´ãªãºã ã¯ããã¤ãããã¨æãã¾ããã1ã¤ã¯æ·±ãåªå
æ¢ç´¢ã
AtCoderã®è§£èª¬ã§DFSã¨ããç¨èªãåºã¦ãããã¨ãå°è±¡ã«æ®ã£ã¦ãã¾ãï¼depth-first searchï¼ã
å¦çæ代ã«å¦ãã æ°ã¯ããã®ã§ããããå帰ãã¨ããæ¦å¿µã«è¦ææèããããDFSãèªåã®ãã®ã«ã§ãã¦ããªãæè¦ã§ããã
å¿
è¦ã«è¿«ããã¦ä»åã®ç´ æ¯ãã§ãã
ãåé¡è§£æ±ºåãéããï¼ã¢ã«ã´ãªãºã ã¨ãã¼ã¿æ§é ã
ç©ãèªããæã«åãã¾ããã
13ç« ãã°ã©ãæ¢ç´¢ã§ãã
ã13.3 å帰é¢æ°ãç¨ããæ·±ãåªå
æ¢ç´¢ããä»ã®ç§ã«ã¯ãã³ãã·ã£ã§ããã
C++ã®å®è£ ä¾
Pythonã§åçµï¼å帰ã使ã£ãDFS
以ä¸ã®ã°ã©ããæ·±ãåªå æ¢ç´¢ãã¾ãã
graph LR 0-->5 1-->6 1-->3 2-->7 2-->5 3-->7 3-->0 4-->1 4-->6 4-->2 6-->7 7-->0
- 8é ç¹ï¼çªå·0ã7ï¼ã12辺
- graphã¯ãªã¹ãã®ãªã¹ã
graph[0]
ã®[5]
ã¯ãé ç¹0ããé ç¹5ã¸ã®è¾ºããããã¨ã示ãgraph[1]
ã®[6, 3]
ã¯ãé ç¹1ããé ç¹6ãé ç¹3ã¸ã®2ã¤ã®è¾ºããããã¨ã示ã
- åé ç¹ã訪åæ¸ã¿ãã表ãé
å
seen
- 訪åæ¸ã¿ãªãã¹ãããï¼å度å¦çããªãï¼
dfs
é¢æ°ï¼å帰é¢æ°ï¼ã§é ç¹iã®å¦ç- é ç¹iã訪åæ¸ã¿ã«ãã
- é ç¹iãã辿ããé ç¹ã«ã¤ãã¦
- 1ã¤1ã¤å¦ç
- 訪åæ¸ã¿ã§ãªããã°
dfs
ãå帰å¼ã³åºã
- ãã¼ãã1åãã¤ãã©ãããã«
for
æã§range
ãåãã¦ãã
å®è¡çµæ
% hatch run python script.py # Python 3.12.0 ã§å®è¡ããã¾ãã main: Visiting node 0 dfs: Visiting node 0 dfs: Visiting node 5 main: Visiting node 1 dfs: Visiting node 1 dfs: Visiting node 6 dfs: Visiting node 7 dfs: Visiting node 3 main: Visiting node 2 dfs: Visiting node 2 main: Visiting node 3 main: Visiting node 4 dfs: Visiting node 4 main: Visiting node 5 main: Visiting node 6 main: Visiting node 7
- é ç¹0ããå§ããï¼0, 1, 2, ...ï¼
- é ç¹0ããé ç¹5ã«è¾¿ãã
- é ç¹5ã«ã¤ãã¦dfs
- é ç¹5ã¯çµç«¯
- é ç¹5ã«ã¤ãã¦dfs
- é ç¹0ããé ç¹5ã«è¾¿ãã
- 次ã¯é ç¹1
- é ç¹1ããé ç¹6, 3ã«è¾¿ãã
- é ç¹6ããé ç¹7ã«è¾¿ãã
- é ç¹7ããé ç¹0ã«è¾¿ãããã0ã¯è¨ªåæ¸ã¿
- é ç¹3ããé ç¹7, 0ã«è¾¿ãã
- ãããã訪åæ¸ã¿
- é ç¹6ããé ç¹7ã«è¾¿ãã
- é ç¹1ããé ç¹6, 3ã«è¾¿ãã
- 次ã¯é ç¹2
- 以ä¸çç¥
é¢é£ãªã½ã¼ã¹
è³¼èªï¼but ç©ãèªï¼ãã¦ããããã¡ããããã®ããã°ã®åºçªã§ãããã®ã§ã¯ã¨æãã¾ããã
以ä¸ãçºããã¨ããå¦ã³ãããã¤ãããã¾ããã
ã°ã©ãæ¢ç´¢ã®åé¡ã¨ãã¦ã人çã§æåã«è§£ãããåé¡ï¼ï¼
ï¼ä¸ã®ã¹ã¯ãªããã¯ãDFSã«ã¾ãåãåãããã«å ¥åã®å¦çãçç¥ãããã§ãããï¼
ãé£æ¥ãªã¹ã表ç¾ãããæ¨ã¯ã°ã©ãã®ä¸ç¨®ã§ãã®ã§ã(ç¥) DFSã»BFS ãã§ãã¾ããããªã©çè«é¢ã®ç¥èè£å¼·ã¨ãªãè¨äºã§ã
çµããã«
è¦ææèã®ãã£ããå帰ã使ã£ãæ·±ãåªå
æ¢ç´¢ã«åãåãã¾ããã
ä»åãä½åº¦ç®ã«ãªããã¯åããã¾ããããåè¦æãããé£æ¥ãªã¹ã表ç¾ãå帰ã«é©ããã«æ¸ã¿ãC++ã®ãµã³ãã«ã³ã¼ããPythonã§æ¸ãæããã¾ã§ã§ãã¾ããï¼ãããå¹´ã®åï¼ã
é£ããå«ããã¦ããé£æãæã決ãã¦é£ã¹ã¦ã¿ãããé£ã¹ãããªããã¨å
¨ç¶ãªãã£ãã¨ããæãã§ã