using System;
using System.Collections.Generic;
class Solution {
private int[][] mover
= { new int[] { 1, 0 }, new int[] { 0, 1 },
new int[] { -1, 0 }, new int[] { 0, -1 },
new int[] { 1, 1 }, new int[] { -1, -1 },
new int[] { 1, -1 }, new int[] { -1, 1 } };
private bool dfs(int x, int y, string word,
bool[][] visited, char[][] board)
{
if (word.Length == 0) {
return true;
}
visited[x][y] = true;
bool sol = false;
foreach(int[] move in mover)
{
int curr_x = move[0] + x;
int curr_y = move[1] + y;
if (0 <= curr_x && curr_x < board.Length
&& 0 <= curr_y
&& curr_y < board[0].Length) {
if (board[curr_x][curr_y] == word[0]
&& !visited[curr_x][curr_y]) {
string s = word.Substring(1);
sol |= dfs(curr_x, curr_y, s, visited,
board);
}
}
}
visited[x][y] = false;
return sol;
}
public IList<string> FindWords(char[][] board,
string[] words)
{
IList<string> ans = new List<string>();
bool[][] visited = new bool[board.Length][];
for (int i = 0; i < board.Length; i++) {
visited[i] = new bool[board[0].Length];
}
for (int i = 0; i < words.Length; i++) {
for (int j = 0; j < board.Length; j++) {
for (int k = 0; k < board[0].Length; k++) {
if (board[j][k] == words[i][0]) {
string s = words[i].Substring(1);
if (dfs(j, k, s, visited, board)) {
ans.Add(
$
"{words[i]} -> {{{j},{k}}}");
}
}
}
}
}
return ans;
}
}
class Program {
static void Main(string[] args)
{
char[][] board
= { new char[] { 'o', 'a', 'a', 'n' },
new char[] { 'e', 't', 'a', 'e' },
new char[] { 'i', 'h', 'k', 'r' },
new char[] { 'i', 'f', 'l', 'v' } };
string[] words = { "oath", "pea", "eat", "rain" };
Solution solver = new Solution();
IList<string> ans = solver.FindWords(board, words);
foreach(string part in ans)
{
Console.WriteLine(part);
}
}
}