简体   繁体   中英

Searching through 2D array horizontally, vertically, and diagonally (both directions) in Java

I am having difficulty with this program I am trying to write. I found many similar problems and solutions online, but they weren't exactly what I was looking for.

There is a text file that my program reads and turns into a char 2D array.

Sample text file:

HFELOJF
ESFOIGD
LSDIOGS
LTDMGER
OEROFFT
SFDLKEG

Then I give it a word such as "hello", and the program prints out weather or not the word exists in the array. Sort of like a word search.

I need to be able to search horizontally, vertically and diagonally. But the word can also be backwards in all 3 cases.

I have started with 2 for loops that start for the top left and work its way to the end.

Inside the 2nd for-loop I have 3 while-loops to deal with: horizontal, vertical and diagonal text. But I just realized that it doesn't work if the word is in reverse. Now in order for me to fix this, I have to construct 3 other while loops to work with my code.

I just find this very repetitive and think there must be a simpler way. But I have been staring at this problem for hours and haven't come up with a brighter idea.

If I continue with what I have, I would have 2 for-loops and 6 while-loops inside the second for-loop which I find to be very messy and repetitive and extra code. Is there a better, faster and more effective way in doing such a problem?

Appreciate all the help and information I can get!

如果你只是想反过来​​检查

String reverse = new StringBuffer(string).reverse().toString();

Here is how I would do it. Loop through each letter. Pretend that letter is the start or end letter of the word. So skip it if it is not either 'h' or 'o' in the case of "hello". Then for each letter check the diagonals, horizontal, and vertical directions. Also if you this whole reverse thing bothers you ignore it. Just search for the letter 'h' and make sure you check all directions from that letter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM